'Add / Remove key-value pairs from a Map
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
Solution 1:[1]
Add to Map
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:[2]
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 mapMap.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 map
variable 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:[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}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 |