'Loop through a Map's key-value pairs

How to iterate over a map's key-value pairs in Elixir?

This doesn't work:

my_map = %{a: 1, b: 2, c: 3}

Enum.each my_map, fn %{k => v} ->
    IO.puts "#{k} --> #{v}"
end


Solution 1:[1]

Turns out you iterate over a Map exactly like you do over a Keyword List (i.e. you use a tuple):

Enum.each(%{a: 1, b: 2, c: 3}, fn {k, v} ->
  IO.puts("#{k} --> #{v}")
end)

Comprehensions also work:

for {k, v} <- %{a: 1, b: 2, c: 3} do
  IO.puts("#{k} --> #{v}")
end

Note: If you use Enum.map/2 and return a tuple, you'll end up with a Keyword List instead of Map. To convert it into a map, use Enum.into/2.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1