Sub topic 5
Building dictionaries with dict comprehensions
This chapter assumes you can write a for loop over range and over a list. It also assumes you know how to read and assign dictionary entries, and that you have seen list comprehensions in the earlier chapters. A dict comprehension uses the same pattern, but each item produces a key and a value instead of a single element.
The syntax
A dict comprehension is written in curly braces. A key: value pair comes first, followed by one or more for clauses.
words = ["apple", "banana", "cherry"]
lengths = {w: len(w) for w in words}
print(lengths) # {'apple': 5, 'banana': 6, 'cherry': 6}This is the same as the loop below. The comprehension replaces the empty dictionary, the loop, and the assignment.
lengths = {}
for w in words:
lengths[w] = len(w)The colon is what separates a dict comprehension from a set comprehension. {w for w in words} builds a set. {w: 1 for w in words} builds a dict.
Filtering with a trailing if
A trailing if works as it does in a list comprehension. It decides which items are used, and it runs before the key and value are computed.
words = ["apple", "banana", "cherry"]
long_words = {w: len(w) for w in words if len(w) > 5}
print(long_words) # {'banana': 6, 'cherry': 6}Choosing a value with if/else
An if/else placed after the colon is a conditional expression. It picks the value for every item, so no item is dropped.
parity = {n: "even" if n % 2 == 0 else "odd" for n in range(4)}
print(parity) # {0: 'even', 1: 'odd', 2: 'even', 3: 'odd'}Only the value is conditional here. The key is still n for every item.
Common sources of pairs
Dict comprehensions are most useful when you start from data that already has a pair shape. Three sources come up often:
- Two parallel lists, combined with
zip. - An existing dictionary, read with
.items(). - A list of records, where one field becomes the key.
names = ["Ada", "Grace", "Linus"]
scores = [92, 88, 75]
by_name = {name: score for name, score in zip(names, scores)}
print(by_name) # {'Ada': 92, 'Grace': 88, 'Linus': 75}
passed = {name: score for name, score in by_name.items() if score >= 80}
print(passed) # {'Ada': 92, 'Grace': 88}The second comprehension shows the usual way to transform a dictionary. You cannot edit a dictionary while looping over it, so you build a new one.
Duplicate keys: the later item wins
A dictionary can hold each key only once. If two items produce the same key, the later one overwrites the earlier one. This happens often when you invert a mapping, because values are not guaranteed to be unique.
words = ["apple", "banana", "cherry"]
lengths = {w: len(w) for w in words}
inverted = {length: w for w, length in lengths.items()}
print(inverted) # {5: 'apple', 6: 'cherry'}Both banana and cherry have length 6. cherry comes later, so it replaces banana. The entry for key 6 also stays in the position where it was first inserted, because dictionaries keep insertion order and an overwrite does not move the key.
Keys must be hashable
Keys must be hashable. Strings, numbers, and tuples of those are fine. A list is not hashable, so this raises TypeError: unhashable type: 'list':
bad = {[n]: n for n in range(3)}Use a tuple instead: {(n,): n for n in range(3)}.
When to keep the loop
A dict comprehension should compute one key and one value from each item. If you need several statements, or you want to log or update something while you build the result, use a regular loop. The comprehension would turn into a long, dense line.
Exercise
What does {len(w): w for w in ["kiwi", "plum", "fig"]} produce, and why does it have only two entries?
Show answer
It produces {4: 'plum', 3: 'fig'}. "kiwi" and "plum" both have length 4, so both items produce the key 4. The later item, "plum", overwrites "kiwi". The key 4 stays first because it was inserted first.
Exercise
Given prices = {"tea": 3.0, "coffee": 4.5, "juice": 5.0}, write a dict comprehension that keeps only items costing less than 5 and adds 10% to each price.
Show answer
{item: price * 1.1 for item, price in prices.items() if price < 5}. The if filters the items. The value expression changes the price. The result has the keys "tea" and "coffee", and the new prices may show small floating-point rounding differences.