Elixir Language Lists Keyword Lists


Keyword lists are lists where each item in the list is a tuple of an atom followed by a value.

keyword_list = [{:a, 123}, {:b, 456}, {:c, 789}]

A shorthand notation for writing keyword lists is as follows:

keyword_list = [a: 123, b: 456, c: 789]

Keyword lists are useful for creating ordered key-value pair data structures, where multiple items can exist for a given key.

The first item in a keyword list for a given key can be obtained like so:

iex> keyword_list[:b]

A use case for keyword lists could be a sequence of named tasks to run:

defmodule TaskRunner do
  def run_tasks(tasks) do
    # Call a function for each item in the keyword list.
    # Use pattern matching on each {:key, value} tuple in the keyword list
    Enum.each(tasks, fn
      {:delete, x} ->
        IO.puts("Deleting record " <> to_string(x) <> "...")
      {:add, value} ->
        IO.puts("Adding record \"" <> value <> "\"...")
      {:update, {x, value}} ->
        IO.puts("Setting record " <> to_string(x) <> " to \"" <> value <> "\"...")

This code can be called with a keyword list like so:

iex> tasks = [
...>   add: "foo",
...>   add: "bar",
...>   add: "test",
...>   delete: 2,
...>   update: {1, "asdf"}
...> ]

iex> TaskRunner.run_tasks(tasks)
Adding record "foo"...
Adding record "bar"...
Adding record "test"...
Deleting record 2...
Setting record 1 to "asdf"...