Maps

Maps are key-value data structures, where both the key and the value can be of any type. They're similar to hashes in Ruby and dictionaries in Python. To create a map, you enclose your key-value pairs in %{}, and put a => between the key and the value, as we can see in the following snippet:

iex> %{:name => "Gabriel", :age => 1}%{age: 1, name: "Gabriel"}

In this case, the keys are both of the same type, but this isn't required. If your keys are atoms, you can use the following syntax to make the map declaration simpler:

iex> %{name: "Gabriel", age: 1}%{age: 1, name: "Gabriel"}

To access the value associated with a certain key, put the key inside square brackets in front of the map:

iex> map = %{name: "Gabriel", age: 1}%{age: 1, name: ...

Get Mastering Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.