runtime
62 / 250
lesson 62 Comprehensions · intermediate

Build a dictionary with a comprehension

A dictionary comprehension builds a lookup in one expression: one `key: value` pair for every item.

You'll be able to
  • Build an index from a list of records with {key: value for item in items}
  • Transform a dictionary's keys or values by looping over items()
  • Predict what happens when two items produce the same key
The idea

The Collection Algorithms module built an index, a dictionary from ID to record, with a loop that stored one pair per pass. A dictionary comprehension writes that loop as one expression: {key: value for item in items}. The braces and the colon say *dictionary*; the part before for says which key and which value each item contributes.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · Film titles by ID
movies = [
    {"movie_id": 12, "title": "Glass Echo of Glass", "release_year": 2023},
    {"movie_id": 917, "title": "Wild Archive", "release_year": 2008},
    {"movie_id": 940, "title": "Hidden Orchard", "release_year": 2010},
]
title_of = {movie["movie_id"]: movie["title"] for movie in movies}
print(title_of)
print(title_of[917])

A key has to be a value that can't change, such as a number, a text or a tuple. A list can change, so Python refuses to use it as a key.

example-2.py · A list as a key
movies = [{"title": "Wild Archive", "genres": ["Drama", "Mystery"]}]
by_genres = {movie["genres"]: movie["title"] for movie in movies}
print(by_genres)

The comprehension can also walk another dictionary. for key, value in row.items() unpacks each pair (see Dictionaries & Sets), and the expression in front decides the new pair. This is how you clean up column names that came from a spreadsheet, without changing the original row.

example-3.py · Tidy the column names
def tidy_keys(row):
    return {key.strip().lower(): value for key, value in row.items()}

raw = {" Flight ": "UA2017", "ORIGIN": "LAS", "Dest ": "IAH"}
row = tidy_keys(raw)
print(row)
print(row["origin"], raw["ORIGIN"])

When to use it: building a lookup by ID, or reshaping the keys or values of a dictionary. Mistakes to avoid: forgetting that keys are unique. When two items produce the same key, the later pair replaces the earlier value, exactly as two assignments would. If "City" and "city " both tidy to "city", only one survives, and nothing warns you.

Review
  • {key: value for item in items} builds one pair per item; walk items() to reshape another dictionary.
  • Keys must be unchangeable values such as text, numbers or tuples; a list as a key is a TypeError.
  • When two items give the same key, the later value wins without warning.
  • Next: braces without a colon keep each value only once, in a set.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Build a dictionary with a comprehension — Comprehensions · Runtime