Lesson · Comprehensions & Expressive Iteration
Set & Dictionary Comprehensions
55 min readSet & Dictionary Comprehensions
Set and dictionary comprehensions extend the comprehension model to uniqueness and key-value construction. They are especially useful for transformations where the output collection type expresses the intent.
Learning goals
- Choose between a set and a dict comprehension by asking whether the result needs distinct values or key-value lookup.
- Explain why
{len(word) for word in words}produces three elements from four input words. - Build
{key_expr: value_expr for ...}and state which pair survives when two items collide on the same key. - Rewrite keys or values of an existing dict with
.items()without touching the source mapping. - Add a trailing
ifclause to keep only selected pairs and predict the effect on the result size.
Mental model
Braces decide the output type: a single expression before for builds a set of distinct values, while a key: value pair builds a dictionary. When the source is itself a mapping, iterate .items() so both parts are available, and append an if clause to keep only the pairs you want. Collisions are resolved by equality, not position: a set silently drops a repeated value, and a dict lets the last duplicate key overwrite the earlier entry.
Braces decide set or dict
collisions are resolved by equality
Mental model
the same mechanism as a compact list
{len(word) for word in words} set: distinct values
{word: len(word) for word in words} dict: key-value pairs
↓ transforming an existing mapping
{word.upper(): length for word, length in index.items()}
↓ filtering the pairs
{word: length for word, length in index.items() if length >= 5}Core idea
The left side of the expression is the point: {expr for ...} promises distinctness, {key: value for ...} promises lookup by key. Both eagerly build a brand-new collection and leave the source untouched, and both keep the list comprehension grammar: output first, source second, optional filter third. The extra decision the dict form forces is collision handling: when two items produce the same key, the later pair overwrites the earlier one.
Set comprehensions
A set comprehension evaluates an expression for selected input items and keeps only unique hashable results.
Dict comprehensions
A dictionary comprehension creates key-value pairs with {key_expr: value_expr for ...}. Later duplicate keys replace earlier values just as normal dictionary assignment does.
Transforming mappings
Mapping transformations can operate on keys, values, or both. Iterate over .items() when both parts are needed and decide explicitly how collisions in transformed keys are handled.
Filtering mappings
A dictionary comprehension can keep only selected key-value pairs with a trailing if clause. Filtering builds a new mapping rather than mutating the source during iteration.
Walkthrough
wordsrepeats"apple", so the example carries one duplicate designed to expose collision behavior in both collection types.- In
lengths = {len(word) for word in words}the four iterations compute 5, 6, 4, and 5; the set keeps distinct values, solengthsis{4, 5, 6}and its size is three, not four. - In
index = {word: len(word) for word in words if len(word) >= 5}the filter drops"pear"(length 4); the two"apple"pairs write the same key twice, and the second write replaces the first, leaving{"apple": 5, "banana": 6}. - Predict before running: the number of elements in
lengths, and exactly which words remain inindex.
Experiments to try
- Change
wordsto["fig", "fig", "fig"]and predict both results before running:lengthsis{3}, andindexis empty because the filter rejects every word. - Replace the set comprehension with
[len(word) for word in words]and compare sizes; the brackets keep the duplicate 5, the braces do not. - Reverse the dict comprehension to
{len(word): word for word in words}and work out which word sits under the key 5 after all four iterations; the last write wins. - Rebuild
indexthrough{word.upper(): length for word, length in index.items()}and check that.items()keeps each key paired with its value through the rewrite.
Common mistakes
- Expecting a set comprehension to preserve order or count:
{len(word) for word in words}collapses the repeated length 5 into one element, and the result has no positions to index. - Not noticing which duplicate key survives in a dict comprehension: with
{len(word): word for word in words}, each length keeps only the last word seen, so the output depends on source order rather than on a rule you chose. - Putting an unhashable value into a set comprehension:
{[n] for n in range(3)}raisesTypeError: unhashable type: 'list'because set elements and dict keys must be hashable. - Mutating the source mapping while a comprehension reads it: removing keys from a dict inside the expression that iterates
mapping.items()raisesRuntimeError: dictionary changed size during iteration.
Practice: Easy
- Build
numbers = [1, 2, 2, 3, 3, 3]and write{n for n in numbers}; predict the element count before running and compare it withlen(numbers). - Print
sorted(index)for the worked example's dict and explain why sorting is needed to get a predictable display order. - Build
{word: len(word) for word in ["apple", "banana", "pear", "apple"]}without the filter and check which value the key"apple"holds at the end.
Practice: Medium
- Add
"mango"(length 5) towordsand rebuild{len(word): word for word in words}; name every key that collides and the value that survives for each. - Rewrite
indexas an explicit loop withindex[word] = len(word); compare the output and state what the loop shows about the overwrite that the comprehension hides. - Transform
indexinto{word.upper(): length for word, length in index.items()}, then addif length == 5to the same expression and record which pairs remain.
Practice: Hard
- Build a word frequency map two ways over
"to be or not to be": a loop withcounts[word] = counts.get(word, 0) + 1and a comprehension with{word: words.count(word) for word in set(words)}; explain why the second version rescans the list once per unique word. - Build an inverted index
{word: page for page, text in pages.items() for word in text.split()}frompages = {1: "python rocks", 2: "python tests"}; predict which page"python"receives, explain why the single-pair form cannot keep both, and sketch the dict-of-lists shape that could. - Define a key-collision policy for rewriting dict keys, for example lowercasing them, and implement both branches: last-wins in a comprehension, and merge-values in a loop; add one assertion per branch that pins the chosen behavior.
Lesson checklist
- I can choose between set and dict comprehension braces by what the result must express.
- I can predict how many elements a set comprehension keeps when the input repeats values.
- I can say which pair survives when two items collide on one dict key.
- I can transform an existing mapping through
.items()and filter its pairs without editing the source.
Remember
Set and dictionary comprehensions answer two different questions: one keeps the distinct results, the other builds key-value pairs for lookup. Both reuse the list comprehension grammar and build a new collection eagerly, so the source stays untouched. Choose the collision rule before writing the dict form, because equal keys overwrite silently.
Interview angles
What is the main purpose of **Set comprehensions**?+
A set comprehension evaluates an expression for selected input items and keeps only unique hashable results.
What should you pay attention to when using **Dict comprehensions**?+
A dictionary comprehension creates key-value pairs with {key_expr: value_expr for ...}. Later duplicate keys replace earlier values just as normal dictionary assignment does.
How does **Transforming mappings** fit into this lesson?+
Mapping transformations can operate on keys, values, or both. Iterate over .items() when both parts are needed and decide explicitly how collisions in transformed keys are handled.
In `index = {word: len(word) for word in words if len(word) >= 5}`, both `"apple"` items produce a pair. What happens to them, and what does `index` hold at the end?+
The two pairs write the same key, so the dictionary keeps one entry: the second write replaces the first with the same value. After the filter drops "pear", index is {"apple": 5, "banana": 6}.