elixir

Elixir: How to invert a map (swap keys and values)?


I have a map like this:

%{
  "US" => "United States",
  "CA" => "Canada",
  "NL" => "The Netherlands"
}

I'd like to swap the keys with the values, resulting in a map like this:

%{
  "United States" => "US",
  "Canada" => "CA",
  "The Netherlands" => "NL"
}

What's the best way to do "invert" or "reverse" a map like this? I don't see a dedicated function for it anywhere.


Solution

  • One easy way is to use Map.new. It takes a function where you can specify the new key & value for each pair:

    Map.new(map, fn {key, val} -> {val, key} end)