liveBook · Manning

Map

As explained in Elixir in Action, Third Edition

A map is an Elixir data structure that associates keys with values, with both keys and values allowed to be any term.

A map associates keys with values, allowing any term as either side. It supports dynamically sized key-value data and compact structures representing named fields. section 2.4.6

Use maps according to the failure behavior and update operation required:

  • Create maps with %{}, map literals, or Map.new/1 from two-element tuples. section 2.4.6
  • Read with brackets or Map.get/3; use Map.fetch/2 to distinguish a missing key from a stored value such as :not_found. section 2.4.6
  • Choose Map.fetch!/2 when absence should raise, and Map.put/3, Map.update/4, or Map.delete/2 for changes. section 2.4.6
  • Use dot access and update syntax for known fields; updating a nonexistent field raises a KeyError. section 2.4.6

Squares and named fields

A squares map can associate integer keys with values: %{1 => 1, 2 => 4, 3 => 9}. Map.put(squares, 4, 16) returns a map containing the new pair. A named-field map such as %{name: "Bob", age: 25} supports bob.age and %{bob | age: 26}. section 2.4.6

How Elixir in Action, Third Edition covers it

How deep it goes
Explains construction, lookup, missing-key behavior, updates, and field access without covering the complete Map API.
Examples
Uses empty maps, square-number mappings, Map.new/1, and a named Bob record.
What it assumes
Assumes basic Elixir expressions and terms while establishing maps among the language's built-in complex types.
What you can do after
Apply map literals, Map functions, access operators, and update syntax while choosing explicit missing-key behavior.
How it connects
Connects maps with tuples, lists, keyword lists, Enum, and immutable data.

Also explained in

Compare how 42 books explain Map →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.