Nathaniel Johnson
Nathaniel Johnson

Reputation: 623

Convert two lists of same size to key value pair in elixir

I'm trying to figure out the best way to combine two lists of the same size into a map of key value pairs.

I've been using the same function to handle this case for a while for CSVs and raw SQL queries which return some sort of header list along with row lists.

This is the function I've been using

Enum.zip(list1, list2) |> Enum.into(%{})

For example:

# For CSVS
header = ["column1","column2","column3"]
rows = [["a","b","c"],["d","e","f"]]
Enum.each rows, fn(row) ->                                                                                                                                                                              
  # Map the header to each row field                                                                                                                                                                    
  row = Enum.zip(header, row) |> Enum.into(%{})
  # Do some processing with the row
  IO.inspect row                                                                                                                                            
end

Is there a function in elixir/erlang that will do this for me or is the above combination of zip/into the best way to do it?

Upvotes: 13

Views: 4817

Answers (2)

Nathaniel Johnson
Nathaniel Johnson

Reputation: 623

After discussing with a few people the method I was using is the best way to accomplish mapping lists of keys to lists of values.

Enum.zip(list1, list2) |> Enum.into(%{})

Upvotes: 20

coderVishal
coderVishal

Reputation: 9079

I was having a similar question and i asked it on elixir-lang slack group and got a answer that is exactly like your approach.

What you used is a good solution.For now you have to stick to it.

Upvotes: 3

Related Questions