🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Maps

A map is a collection that stores one value for each key. Keys in a map are often atoms or strings.

A map stores values under atom keys

The %{...} shape creates a map. This map stores a name and an age under atom keys.

person = %{name: "Ana", age: 31}
IO.inspect(person)

Dot and bracket access read a map

Dot access reads a value under an atom key. Bracket access reads any key and gives nil for a key the map does not hold.

person = %{name: "Ana", age: 31}
IO.puts(person.name)
IO.puts(person.age)
IO.inspect(person[:name])
IO.inspect(person[:city])

String keys use the arrow shape

The => arrow pairs a string key with its value. Bracket access with the same string reads the value back.

scores = %{"bo" => 85, "ana" => 90}
IO.inspect(scores)
IO.puts(scores["bo"])
IO.inspect(scores["missing"])

Example

book = %{title: "Dune", pages: 412}
IO.inspect(book)
IO.puts(book.title)
IO.puts(book[:pages])
IO.inspect(book[:author])
labels = %{"isbn" => "978", "lang" => "en"}
IO.inspect(labels)
IO.puts(labels["lang"])

Key points

  • Map literal: The %{...} shape holds key and value pairs, such as %{name: "Ana"}.
  • Atom keys: Atom keys are written as key: value inside a map literal.
  • String keys: String keys are written with the => arrow, such as %{"a" => 1}.
  • Dot access: Use map.key to read a value stored under an atom key.
  • Bracket access: Use map[:key] to read a value for any key, and a missing key gives nil.
  • One value per key: A map stores a single value under each key.

In this example, the book map uses atom keys, so the title reads with dot access and the pages read with bracket access. The missing :author key gives nil. The labels map then uses string keys, and bracket access reads the value stored under "lang".

Note

A keyword list keeps duplicate keys, while a map keeps only one value for each key.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How do you read the value stored under the string key "title" in the map book?