🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Map Functions

Map functions are built-in helpers that read a map or return a new map with changes. They live in the Map module and cover the everyday jobs of getting, adding, removing, and combining keys.

Get a value with a fallback

Map.get reads one key. The third argument is the fallback for a missing key.

person = %{name: "Ana", age: 31}
IO.puts(Map.get(person, :name))
IO.puts(Map.get(person, :city, "unknown"))

Add, remove, and merge keys

Map.put adds a key and Map.delete removes one. Map.merge combines two maps into a new one.

person = %{name: "Ana", age: 31}
updated = Map.put(person, :city, "Oslo")
IO.inspect(Map.delete(updated, :age))
IO.inspect(Map.merge(person, %{age: 32}))

Check a key and fetch its value

Map.has_key? asks whether a key exists. Map.fetch answers with an ok tuple or the atom :error.

person = %{name: "Ana", age: 31}
IO.puts(Map.has_key?(person, :age))
IO.inspect(Map.fetch(person, :name))
IO.inspect(Map.fetch(person, :city))

Example

pairs = [name: "Ana", age: 31]
person = Map.new(pairs)
with_city = Map.put(person, :city, "Oslo")
IO.inspect(Map.keys(with_city))
IO.inspect(Map.values(with_city))
IO.inspect(with_city)

Key points

  • Map.get: Map.get(map, key, default) returns the value for a key or the default when the key is missing.
  • Map.put: Map.put(map, key, value) returns a new map with the key added or replaced.
  • Map.delete: Map.delete(map, key) returns a new map without that key.
  • Map.merge: Map.merge(first, second) combines two maps and the second map wins on shared keys.
  • Map.fetch: Map.fetch(map, key) returns {:ok, value} for a present key and :error for a missing one.
  • Map.new: Map.new(pairs) builds a map from a list of two-item pairs.

In this example, Map.new builds a map from a keyword list of pairs. Map.put adds the :city key, and Map.keys and Map.values list the keys and values of the new map.

Note

Every Map function returns a new map and the original map stays unchanged.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does Map.fetch(%{name: "Ana"}, :city) return?