Putting Things Into Maps in Elixir

Elixir's Map module provides a number of different functions for working with a map. One of those functions is Map.put/3. This function allows you to put a key-value pair into a map.

> pokemon = %{charmander: 22}
%{charmander: 22}
> pokemon = Map.put(pokemon, :squirtle, 9)
%{charmander: 22, squirtle: 9}
> pokemon = Map.put(pokemon, :squirtle, 10)
%{charmander: 22, squirtle: 10}

If the key is new to the map, the key-value pairing is simply added. If the key already exists, then the existing value is replaced by the new value.

The same can be achieved with the Map.merge/2 function.

> pokemon = %{charmander: 22}
%{charmander: 22}
> Map.merge(pokemon, %{squirtle: 9})
%{charmander: 22, squirtle: 9}
> pokemon = Map.merge(pokemon, %{squirtle: 9})
%{charmander: 22, squirtle: 9}
> pokemon = Map.merge(pokemon, %{squirtle: 10})
%{charmander: 22, squirtle: 10}
> pokemon = Map.merge(pokemon, %{squirtle: 11, bulbasaur: 14})
%{bulbasaur: 14, charmander: 22, squirtle: 11}

The advantage of Map.merge/2 is its flexibility. It can be more easily used in different situations. It even allows for adding and replacing multiple key-value pairs at once. Because both arguments are maps, it feels a bit easier to read.

There is also a syntactically-sugary approach that uses the map literal notation and a pipe to replace an existing key-value pair.

> pokemon = %{charmander: 22, squirtle: 9}
%{charmander: 22, squirtle: 9}
> pokemon = %{pokemon | squirtle: 10}
%{charmander: 22, squirtle: 10}

This is the most concise approach, but, again, it only works for replacing a key-value pair. If the key isn't present in the existing map, an error will occur.

There are certainly other functions out there for putting values into maps including Kernel.put_in/3 and Map.get_and_update/3. Nevertheless, the above techniques are the ones for which I find myself most frequently reaching.