1.2.35 · D3Introduction to Programming (Python)

Worked examples — Dictionary and set comprehensions

4,465 words20 min readBack to topic

This page assumes only what the parent parent note built. If a term feels new, it is re-earned here.


The scenario matrix

Every comprehension question is really one row of this table. Each cell is a distinct behaviour you must be able to predict on sight.

# Case class What makes it tricky Example that hits it
A Basic dict, unique keys nothing — the baseline Ex 1
B Key collision (two items, same key) later value overwrites Ex 2
C Collision fixed by grouping into lists keep everything Ex 3
D Filter if at the end some items produce no entry Ex 4
E Ternary if/else in the value every item entered, value chosen Ex 5
F Set comprehension, duplicate values dropped count shrinks Ex 6
G Empty / degenerate input empty iterable, {} trap Ex 7
H Nested comprehension (two fors) Cartesian sweep Ex 8
I Unhashable key — the crash case list can't be a key Ex 9
J Real-world word problem + exam twist reading intent into syntax Ex 10
K Chained filters (if cond1 if cond2) both must pass Ex 11

Look at Figure s01 below: it labels the three parts of a comprehension in the exact order you should read them — the black arrows point to the for (part 1) and the if (part 2), and the red arrow singles out the head with its colon (part 3), the piece that decides dict-vs-set. Trace the arrows in numbered order before you read any real code.

Figure — Dictionary and set comprehensions

Example 1 — Baseline dict, unique keys (cell A)


Example 2 — Key collision, later wins (cell B)

Look at Figure s02 below: six input boxes (x=0..5) at the top fan down into three key buckets. Six thin black arrows would land, but only the red arrows — the last write into each bucket — survive, and the red -> 3 / -> 4 / -> 5 under the buckets is the final stored value. The picture is the "last write wins" rule made visible.

Figure — Dictionary and set comprehensions

Example 3 — Fix the collision: keep everything with lists (cell C)


Example 4 — Filter if at the end (cell D)


Example 5 — Ternary in the value slot (cell E)


Example 6 — Set comprehension, duplicates collapse (cell F)


Example 7 — Empty & degenerate inputs (cell G)


Example 8 — Nested comprehension (two fors) (cell H)

Look at Figure s03 below: the 3×3 grid draws every (i, j) combination as a dot, with the tiny product i*j written beside it — i climbs the vertical axis (outer loop), j runs along the horizontal (inner loop). The single red dot marks key (2, 3), whose stored value is 6, so you can see that nested fors enumerate a rectangle of keys.

Figure — Dictionary and set comprehensions

Example 9 — The unhashable-key crash (cell I)


Example 10 — Word problem + exam twist (cell J)


Example 11 — Chained filters if … if … (cell K)


Putting the matrix back together

yes

no

yes

fix

yes

no

yes

A comprehension

Colon present?

Dict comprehension

Set comprehension

Keys collide?

Last write wins

Group into lists

Trailing if?

Filter drops items

All items kept

Value has if else?

Ternary chooses value

Key must be hashable

Two ifs mean AND

Recall Active recall — cover the answers

How many entries does {x % 3: x for x in range(6)} produce? ::: 3 — keys 0,1,2, each with its last value 3,4,5 In what order do those keys print, and why? ::: 0, 1, 2 — their first-insertion order (dicts preserve insertion order since Python 3.7) How do you keep all colliding items instead of overwriting? ::: Accumulate into list values (e.g. defaultdict(list)), then snapshot into a dict A trailing if vs a value-ternary — which drops items? ::: The trailing if drops items; the ternary keeps all and only changes values {len(w) for w in ["hi","cat","dog"]} gives what? ::: {2, 3} — the duplicate length 3 collapses What does {k: v for k, v in []} return, and of what type? ::: {}, an empty dict (syntax has a colon) Why does {[i]: i for i in range(3)} crash? ::: A list is unhashable (mutable), so it cannot be a dict key What do two back-to-back ifs in one comprehension mean? ::: AND — an item must pass both conditions To turn a set-of-names into a dict-of-names→0, what single edit is needed? ::: Add a colon and a value: {name: 0 for ...} What does ** mean in Python? ::: The power (exponent) operator — n**2 is , n**3 is


Connections

  • Parent: Dictionary and set comprehensions — the core rules this page stress-tests
  • List comprehensions — same syntax family with []
  • Dictionaries in Python — the collision / last-write-wins behaviour and insertion order
  • Sets in Python — automatic uniqueness in Example 6
  • Generator expressions — lazy (...) cousin, no collision handling since nothing is stored
  • Hashing and hashable types — why Example 9 crashes and what "hashable" means
  • Ternary conditional expression — the value-chooser in Example 5