How to create a map from a list of two item tuples in Elixir

Elixir

Elixir Problem Overview


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?

Elixir Solutions


Solution 1 - Elixir

The simplest way to do this is:

Enum.into(list, %{})

Solution 2 - Elixir

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

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

Solution 3 - Elixir

I've just got it:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsiddhadevView Question on Stackoverflow
Solution 1 - ElixirbitwalkerView Answer on Stackoverflow
Solution 2 - Elixirdenis.peplinView Answer on Stackoverflow
Solution 3 - ElixirsiddhadevView Answer on Stackoverflow