72
votes

What would be an elegant way for converting a list of two item tuples like [{1,2},{3,4}] into the map %{1=>2, 3=>4}?

Keyword list would be trivial, but what if we have arbitrary keys?

3
Came here from google looking to convert from keyword list to Map. Could you elaborate on this trivial operation? :)Jay

3 Answers

126
votes

The simplest way to do this is:

Enum.into(list, %{})
23
votes

Map module also supports such lists as a parameter to a new function:

iex> Map.new([{1, 2}, {3, 4}])
%{1 => 2, 3 => 4}
4
votes

I've just got it:

list = [{1,2},{3,4}]
themap = for e <- list, into: %{}, do: e