🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Keyword Lists

A keyword list is a list of key and value pairs where each key is an atom. Each pair is a two-value tuple, and the list keeps the pairs in order.

A keyword list pairs keys with values

The key: value shape builds a keyword list. Keyword.get reads the value stored under a key.

options = [name: "Ana", age: 31]
IO.inspect(options)
IO.inspect(Keyword.get(options, :name))

A default covers a missing key

Keyword.get takes a third value as a fallback for a missing key. Keyword.has_key? reports whether a key is present at all.

settings = [theme: "dark", retries: 3]
IO.inspect(Keyword.get(settings, :theme))
IO.inspect(Keyword.get(settings, :language, "en"))
IO.inspect(Keyword.has_key?(settings, :retries))
IO.inspect(Keyword.has_key?(settings, :language))

Duplicate keys are kept in order

A keyword list may hold the same key twice. Keyword.get returns the first matching value, and Keyword.keys lists every key.

tags = [color: "red", size: "large", color: "blue"]
IO.inspect(Keyword.keys(tags))
IO.inspect(Keyword.get(tags, :color))
IO.puts(length(tags))

Example

config = [host: "localhost", port: 8080, host: "example.com"]
IO.inspect(Keyword.get(config, :host))
IO.inspect(Keyword.get(config, :port))
IO.inspect(Keyword.get(config, :timeout, 30))
IO.inspect(Keyword.keys(config))

Key points

  • Keyword literal: Pairs are written as key: value inside square brackets.
  • Atom keys: Every key in a keyword list is an atom.
  • Keyword.get: Use Keyword.get(list, key) to read the first value stored under a key.
  • Default value: Keyword.get(list, key, default) returns the default when the key is missing.
  • Keyword.has_key?: Use Keyword.has_key?(list, key) to check whether a key is present.
  • Duplicate keys: The same key may appear more than once, and Keyword.keys(list) returns every key in order.

In this example, the config holds the key :host twice, and Keyword.get returns its first value. The port reads as 8080, and the missing :timeout key falls back to the default 30. The last line lists all three keys in order, duplicates included.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does Keyword.get([mode: "fast"], :speed, "slow") return?