TExcelTAD
Home › Elixir › Elixir Keyword Lists

Elixir Keyword Lists

A keyword list is a list of 2-element tuples whose first element is an atom. Elixir gives it special, very readable syntax, and uses it everywhere for options passed to functions.

elixir · try it yourself
opts = [size: 10, color: :red]

IO.inspect(opts)
IO.inspect(opts == [{:size, 10}, {:color, :red}])
IO.inspect(opts[:color])
IO.inspect(opts[:missing])
[size: 10, color: :red]
true
:red
nil

[size: 10, color: :red] is exactly the list [{:size, 10}, {:color, :red}]. The key: value form is just nicer to write.

Properties

Property Keyword list Map
Keys atoms only any value
Order kept as written not guaranteed
Duplicate keys allowed not allowed
Lookup speed linear (it is a list) fast
Typical use function options, small configs data, larger collections

Because order and duplicates are kept, keyword lists are perfect for options and for DSLs (for example Ecto queries: from u in User, where: u.age > 18, select: u.name).

Keywords as function options

When the last argument of a call is a keyword list, the square brackets can be left out. You have already done this with if:

elixir · try it yourself
IO.inspect([3, 1, 2], label: "numbers", charlists: :as_lists)

IO.puts(String.split("a-b-c", "-", parts: 2) |> inspect())

# `if` is a macro that receives [do: ..., else: ...]
result = if true, do: "yes", else: "no"
IO.puts(result)
IO.puts(if(false, [{:do, "yes"}, {:else, "no"}]))
numbers: [3, 1, 2]
["a", "b-c"]
yes
no

The last line is the same if written with the full list syntax. It shows that do:/else: really are keywords.

The Keyword module

elixir · try it yourself
defaults = [timeout: 5_000, retries: 3, verbose: false]
given = [retries: 5, verbose: true]

config = Keyword.merge(defaults, given)
IO.inspect(config)

IO.inspect(Keyword.get(config, :timeout))
IO.inspect(Keyword.get(config, :port, 4000))
IO.inspect(Keyword.fetch(config, :port))
IO.inspect(Keyword.put(config, :timeout, 10_000))
IO.inspect(Keyword.delete(config, :verbose))
IO.inspect(Keyword.keys(config))
[timeout: 5000, retries: 5, verbose: true]
5000
4000
:error
[timeout: 10000, retries: 5, verbose: true]
[timeout: 5000, retries: 5]
[:timeout, :retries, :verbose]

Keyword.get/3 takes a default for missing keys, which makes the "defaults + overrides" pattern above very common in library code.

Duplicate keys

A keyword list may contain the same key twice. Access with [] or Keyword.get/2 returns the first one; Keyword.get_values/2 returns all:

elixir · try it yourself
headers = [accept: "text/html", accept: "application/json", host: "example.com"]

IO.inspect(headers[:accept])
IO.inspect(Keyword.get_values(headers, :accept))
IO.inspect(Keyword.put(headers, :accept, "*/*"))
"text/html"
["text/html", "application/json"]
[accept: "*/*", host: "example.com"]

Keyword.put/3 removes all existing entries for the key before adding the new one.

Validating options

Libraries often accept only known options. Keyword.validate/2 checks the keys and fills in defaults in one call:

elixir · try it yourself
IO.inspect(Keyword.validate([port: 8080], port: 4000, host: "localhost"))
IO.inspect(Keyword.validate([prot: 8080], port: 4000, host: "localhost"))
{:ok, [host: "localhost", port: 8080]}
{:error, [:prot]}

Common mistakes

  • Pattern matching on keyword lists: [size: s] = opts only matches a list with exactly that one key in that position. Use Keyword.get/3 or opts[:size] instead.
  • Using keyword lists for big data sets: lookups are linear. Use a map.
  • Using string keys: ["size": 1] actually creates the atom :size. A list with string keys, [{"size", 1}], is just a list of tuples, not a keyword list.

Test yourself

What is [a: 1, b: 2] really?

  1. A map
  2. [{:a, 1}, {:b, 2}]
  3. A tuple of tuples
  4. A struct

What does [color: :red, color: :blue][:color] return?

  1. :blue
  2. :red
  3. [:red, :blue]
  4. An error: duplicate key

Why are keyword lists used for function options?

  1. They are faster than maps
  2. They keep order, allow duplicates and have a clean key: value syntax as the last argument
  3. Maps can't hold atoms
  4. They are the only collection that functions can receive