Add / Remove key-value pairs from a Map

Inserting Multiple Key-Value Pairs

If you have an Enumerable of key-value pairs, you can use Map.new/1 to create a new map:

iex> values = [a: 1, b: 2, c: 3]
[a: 1, b: 2, c: 3]
iex> Map.new(values)
%{a: 1, b: 2, c: 3}

To add to an existing map, maps implement the Collectable protocol, so you can use Enum.into/2:

iex> map = %{existing: "value"}
%{existing: "value"}
iex> Enum.into(values, map)
%{a: 1, b: 2, c: 3, existing: "value"}

Or alternatively use a comprehension:

iex> for {k, v} <- values, into: map, do: {k, v}
%{a: 1, b: 2, c: 3, existing: "value"}

Deleting Multiple Keys

For dropping multiple keys at once, there is Map.drop/2:

iex> map = %{a: 1, b: 2, c: 3, d: 4, e: 5}
%{a: 1, b: 2, c: 3, d: 4, e: 5}
iex> Map.drop(map, [:a, :c])
%{b: 2, d: 4, e: 5}

Add to Map

Use Map.put(map, key, value):

map = Map.put(map, :d, 4)
#=> %{a: 1, b: 2, c: 3, d: 4}

Remove from Map

Use Map.delete(map, key):

map = Map.delete(map, :b)
#=> %{a: 1, c: 3}

Your issue

Don't forget that variables are immutable in Elixir.

So the following code doesn't make sense, because you can't directly change map or map[:d]'s value like this:

map[:d] = 4

Solution

Here are the functions you can use instead:

  • Map.put(map, key, value) adds an element to a map

  • Map.delete(map, key) removes an element from a map

How to use these functions?

Since Elixir variables are immutable, these functions return a new map, instead of directly changing your map. Example:

iex(1)> map = %{a: 1, b: 2, c: 3}
%{a: 1, b: 2, c: 3}
iex(2)> Map.put(map, :d, 4)
%{a: 1, b: 2, c: 3, d: 4}
iex(3)> map
%{a: 1, b: 2, c: 3} # map is unchanged

So if you want to "change" your map, you need to replace your old mapvariable by the new map returned by Map.put() or Map.delete(). Example:

iex(1)> map = %{a: 1, b: 2, c: 3}
%{a: 1, b: 2, c: 3}
iex(2)> map = Map.put(map, :d, 4)
%{a: 1, b: 2, c: 3, d: 4}
iex(3)> map = Map.delete(map, :a)
%{b: 2, c: 3, d: 4}

Tags:

Elixir