Add / Remove key-value pairs from a Map

29,374

Solution 1

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}

Solution 2

Your problem

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:

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}

Solution 3

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}
Share:
29,374
Sheharyar
Author by

Sheharyar

Now among the top 5 users from Pakistan!

Updated on July 11, 2022

Comments

  • Sheharyar
    Sheharyar almost 2 years

    How to add (and remove) key-value pairs in an Elixir map? This does not work:

    map = %{a: 1, b: 2, c: 3}
    
    map[:d] = 4