TExcelTAD
Home › Elixir › Elixir Maps

Elixir Maps

A map is Elixir's key-value store. Keys can be any value (atoms, strings, numbers, even tuples), each key appears once, and lookups are fast. Maps are created with %{}.

elixir · try it yourself
prices = %{"apple" => 0.5, "bread" => 2.25, "milk" => 1.1}
IO.inspect(prices["bread"])
IO.inspect(prices["caviar"])
IO.inspect(map_size(prices))

point = %{x: 3, y: 4}
IO.inspect(point.x)
IO.inspect(point[:y])
2.25
nil
3
3
4

There are two key syntaxes:

  • %{"apple" => 0.5}: the general key => value form, for any key type.
  • %{x: 3}: a shortcut when all keys are atoms (%{:x => 3} is the same map).

With atom keys you can use map.key. It raises KeyError if the key is missing, which catches typos early. map[key] returns nil for a missing key.

Updating maps

Maps are immutable, so "updating" returns a new map:

elixir · try it yourself
user = %{name: "Ravi", plan: :free, logins: 3}

upgraded = %{user | plan: :pro}       # update existing key(s) only
IO.inspect(upgraded)

with_email = Map.put(user, :email, "ravi@example.com")
IO.inspect(Map.keys(with_email))

IO.inspect(Map.update(user, :logins, 1, &(&1 + 1)))
IO.inspect(Map.delete(user, :plan))
IO.inspect(user)                       # the original is unchanged

try do
  %{user | age: 30}
rescue
  e in KeyError -> IO.puts(Exception.message(e))
end
%{name: "Ravi", plan: :pro, logins: 3}
[:name, :plan, :logins, :email]
%{name: "Ravi", plan: :free, logins: 4}
%{name: "Ravi", logins: 3}
%{name: "Ravi", plan: :free, logins: 3}
key :age not found

%{map | key: value} only works for keys that already exist, so it is the safe way to update fields. Map.put/3 adds or replaces any key. Map.update/4 applies a function to the current value (or inserts the default 1 if the key is missing).

The Map module

elixir · try it yourself
stock = %{"pens" => 40, "paper" => 0, "ink" => 12}

IO.inspect(Map.get(stock, "pens"))
IO.inspect(Map.get(stock, "staples", 0))
IO.inspect(Map.fetch(stock, "ink"))
IO.inspect(Map.has_key?(stock, "paper"))
IO.inspect(Map.merge(stock, %{"ink" => 20, "tape" => 5}))
IO.inspect(Map.filter(stock, fn {_item, qty} -> qty > 0 end))
IO.inspect(Map.to_list(%{b: 2, a: 1}) |> Enum.sort())
40
0
{:ok, 12}
true
%{"ink" => 20, "paper" => 0, "pens" => 40, "tape" => 5}
%{"ink" => 12, "pens" => 40}
[a: 1, b: 2]

Iterating over a map

Enum functions treat a map as a collection of {key, value} tuples. The iteration order is not something to rely on, so sort when the order matters:

elixir · try it yourself
scores = %{"Mia" => 88, "Leo" => 95, "Ana" => 72}

scores
|> Enum.sort_by(fn {_name, score} -> -score end)
|> Enum.each(fn {name, score} -> IO.puts("#{name}: #{score}") end)

total = Enum.reduce(scores, 0, fn {_name, score}, acc -> acc + score end)
IO.puts("total: #{total}")

curved = Map.new(scores, fn {name, score} -> {name, min(score + 5, 100)} end)
IO.inspect(curved["Leo"])
Leo: 95
Mia: 88
Ana: 72
total: 255
100

Note: The order in which a map's keys are printed or enumerated is an implementation detail: small maps (up to 32 keys) keep their keys in an internal sorted order, larger maps use a hash order, and atom keys are not even sorted alphabetically. Treat the order as undefined and sort when order matters.

Nested maps

Real data is often nested. get_in/2, put_in/2 and update_in/2 reach into nested structures:

elixir · try it yourself
config = %{
  db: %{host: "localhost", port: 5432},
  cache: %{ttl: 60}
}

IO.inspect(config.db.port)
IO.inspect(get_in(config, [:cache, :ttl]))

config = put_in(config.db.host, "db.internal")
config = update_in(config, [:cache, :ttl], &(&1 * 10))
IO.inspect(config.db)
IO.inspect(config.cache)
5432
60
%{port: 5432, host: "db.internal"}
%{ttl: 600}

Pattern matching maps

A map pattern matches any map that has at least the given keys, which makes it great for function arguments:

elixir · try it yourself
greet = fn
  %{name: name, lang: "pt"} -> "Olá, #{name}!"
  %{name: name} -> "Hello, #{name}!"
end

IO.puts(greet.(%{name: "Bruno", lang: "pt", id: 7}))
IO.puts(greet.(%{name: "Kate"}))
Olá, Bruno!
Hello, Kate!

Test yourself

What does %{a: 1}[:b] return?

  1. An error
  2. nil
  3. 0
  4. :error

What happens with %{m | new_key: 1} when m has no :new_key?

  1. The key is added
  2. A KeyError is raised
  3. It returns m unchanged
  4. It returns nil

Which map pattern matches %{id: 1, name: "x", age: 3}?

  1. %{id: 1, name: n}
  2. %{id: 2}
  3. %{id: 1, email: e}
  4. None: patterns must list every key