Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Keyword Lists

keyword_lists.livemd

Keyword Lists

Mix.install([
  {:kino, github: "livebook-dev/kino", override: true},
  {:kino_lab, "~> 0.1.0-dev", github: "jonatanklosko/kino_lab"},
  {:vega_lite, "~> 0.1.4"},
  {:kino_vega_lite, "~> 0.1.1"},
  {:benchee, "~> 0.1"},
  {:ecto, "~> 3.7"},
  {:math, "~> 0.7.0"},
  {:faker, "~> 0.17.0"},
  {:utils, path: "#{__DIR__}/../utils"}
])

Navigation

Return Home Report An Issue

Lesson

Keyword lists are lists with keys. Each key associates with a value.

flowchart
  key1: --> Value1
  key2: --> Value2
  key3: --> Value3

Keyword lists belong to a family of data types known as associative data structures. you’ll also often hear it referred to as a key-value data structure.

In Elixir, the key is an atom, and the value can be any data structure, even another keyword list.

[key: "value"]
[atom: "anything!"]
["You can use quotes for the atom key!": ""]
[snake_case_is_convention: ""]
[ButThatIsNotEnforced: ""]

Keys in a keyword list do not have to be unique.

[my_key: "value", my_key: "value"]

Elixir allows you to work with keyword lists in this nice [key: "value"] syntax. However, keyword lists are actually just a list of tuples where the first element is an atom.

[{:key, "value"}]

In the Elixir cell below, you can see how Elixir converts lists of tuples matching the {:atom, value} syntax into a keyword list.

[{:key, "value"}, {:key, "value"}]

If you break the convention in the keyword list, Elixir reverts to displaying the keyword list as a list of tuples.

[{}, key: "value"]

List order is guaranteed, so the same is true for keyword lists.

Your Turn

In the Elixir cell below, create a keyword list of your favourite super hero. Include their :name and :secret_identity. Replace nil with your answer.

hero = nil

Utils.feedback(:keyword_list_hero, hero)

Keyword List Operators

You can also use -- and ++ with keyword lists.

[one: 1, two: 2] -- [one: 1]

If you add a list to a keyword list, you’ll notice that the keyword list element will evaluate as a tuple again. Remember that keyword lists are simply lists of tuples with an atom and a value.

[one: 1] ++ [1]

Your Turn

In the Elixir cell below, use ++ to add [one: 1] to [two: 2] to make [one: 1, two: 2].

Remove [two: 2] from [one: 1, two: 2] to make [one: 1].

Commit Your Progress

Run the following in your command line from the project folder to track and save your progress in a Git commit.

$ git add .
$ git commit -m "finish keyword lists section"