elixir

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

  • 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}