Loop through a Map's key-value pairs

26,437

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.

Share:
26,437
Sheharyar
Author by

Sheharyar

Now among the top 5 users from Pakistan!

Updated on July 09, 2022

Comments

  • Sheharyar
    Sheharyar over 1 year

    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