Dict comprehensions
A dict comprehension builds a new dict in a single expression, shaped like {key: value for item in iterable}.
Used in 79 lessons of the course, from 00.06.
A dict comprehension creates a dict by looping over an iterable. You write it inside braces, with a key: value pair followed by a for.
Read it from the for first: it takes each item, then the key: value pair says what goes into the dict for each one.
{n: n * n for n in range(3)}
You use it instead of making an empty dict and filling it in a loop, because one line shows the shape of the result. If two items produce the same key, the last one wins.
In the course you will see lines like {name: [m_id ... for m_id, ent in MODEL_LINK.findall(body)]}. It is a dict comprehension whose value is itself a list comprehension. Each name becomes a key and its list of models becomes the value.
Reach for it when: you want to transform or filter data and get a dict back, without a loop full of assignments.
Examples
Common mistake
words = ["a", "b"]
d = {w for w in words}
print(type(d).__name__)Why: Without `key: value`, the braces build a set, not a dict.
How to write it: Write the pair: {w: len(w) for w in words}.
Common mistake
names = ["ana", "al", "ana"]
d = {n: i for i, n in enumerate(names)}
print(d)Why: The key 'ana' repeats and the last value overwrites the first, so the 0 is lost.
How to write it: Use unique keys, or group the values into lists with a loop.
