13

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?

  • 3
    Your solution is good. It is a fairly common approach in most languages. http://rosettacode.org/wiki/Hash_from_two_arrays#Elixir – Gazler Dec 31 '15 at 15:46

2 Answers2

20

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(%{})
3

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.

coderVishal
  • 8,369
  • 3
  • 35
  • 56