Sub topic 8
Dictionary comprehensions
This chapter assumes you can write list comprehensions and loop over dict.items(). It also assumes you know that dictionary keys must be hashable.
The basic form
A dictionary comprehension builds a new dictionary from any iterable in one expression. It is the same idea as a list comprehension, except each result is a key: value pair inside curly braces.
words = ["apple", "bob", "cat"]
lengths = {w: len(w) for w in words}
print(lengths) # {'apple': 5, 'bob': 3, 'cat': 3}The general shape is {key_expr: value_expr for item in iterable}. Python evaluates the key expression and then the value expression for each item. It stores the pair in a new dictionary in the order the iterable produces them.
Filtering with if
An if clause at the end keeps only the items that pass the test.
lengths = {"apple": 5, "bob": 3, "cat": 3}
long_ones = {k: v for k, v in lengths.items() if v > 3}
print(long_ones) # {'apple': 5}Looping over .items() and unpacking into k, v is the usual way to rebuild an existing dictionary. The original is not changed.
Transforming values or keys
You can change values, keys, or both.
prices = {"apple": 0.5, "pear": 0.75}
with_tax = {name: round(price * 1.2, 2) for name, price in prices.items()}
print(with_tax) # {'apple': 0.6, 'pear': 0.9}
shout = {name.upper(): price for name, price in prices.items()}
print(shout) # {'APPLE': 0.5, 'PEAR': 0.75}To pair two sequences, combine zip() with a comprehension. For this simple case, dict(zip(names, scores)) does the same job.
names = ["ana", "ben"]
scores = [90, 72]
print({n: s for n, s in zip(names, scores)}) # {'ana': 90, 'ben': 72}Choosing a value with a conditional expression
An if at the end filters entries out. An if ... else inside the value expression keeps every entry and changes its value. The two positions are different, and mixing them up is a common error.
data = {"a": 5, "b": -2}
clamped = {k: (v if v >= 0 else 0) for k, v in data.items()}
print(clamped) # {'a': 5, 'b': 0}
positive_only = {k: v for k, v in data.items() if v >= 0}
print(positive_only) # {'a': 5}An else after the for clause is a SyntaxError, because the trailing if is a filter and cannot have an else.
Inverting a dictionary
Swapping keys and values is a common use. It only works cleanly when the values are unique and hashable.
colors = {"apple": "red", "cherry": "red", "lime": "green"}
inverted = {color: fruit for fruit, color in colors.items()}
print(inverted) # {'red': 'cherry', 'green': 'lime'}"apple" is lost. Both apple and cherry produce the key "red", and the later pair replaces the earlier value. Python gives no warning.
Common errors
- Duplicate keys overwrite silently. The last pair for a key wins, but the key keeps the position of its first insertion. Check that your key expression is unique, or group the values instead (see the
defaultdictchapter). - Unhashable keys raise
TypeError.{[1, 2]: "x"}fails because lists are not hashable. Use a tuple, as in{tuple(row): i for i, row in enumerate(rows)}. - Curly braces without a colon make a set.
{w for w in words}is a set comprehension. Thekey: valueform makes it a dictionary. - Overly dense comprehensions. If you need several nested
forclauses or a long condition, a plain loop is easier to read and debug. Oneforand at most oneifis a good limit.
Exercise
Given stock = {"apple": 3, "pear": 0, "kiwi": 7}, write a dictionary comprehension that keeps only items with a count above zero and doubles each count. What does it return?
Show answer
{k: v * 2 for k, v in stock.items() if v > 0} returns {'apple': 6, 'kiwi': 14}. The if filters out pear, and the value expression doubles the rest.
Exercise
What does {len(w): w for w in ["a", "b", "cc"]} return, and why?
Show answer
It returns {1: 'b', 2: 'cc'}. The words "a" and "b" both produce the key 1, so the later value "b" replaces "a".