1.2.35Introduction to Programming (Python)

Dictionary and set comprehensions

1,771 words8 min readdifficulty · medium1 backlinks

WHAT are they?


WHY do they exist?

The loop version vs the comprehension version are logically identical. Let's derive that.


HOW: derive the comprehension from a plain loop

Start with the most basic, undeniable way to build a dict — an explicit loop:

squares = {}                 # 1. empty dict
for n in range(5):           # 2. iterate
    squares[n] = n*n         # 3. assign key -> value

Why this works: each pass assigns one key n to value n*n. Now fold those three lines into one expression by moving the assignment target to the front and the loop to the back:

squares = {n: n*n for n in range(5)}
Figure — Dictionary and set comprehensions

Worked examples



Recall Feynman: explain to a 12-year-old

Imagine a vending machine you build yourself. You go down a list of items and, for each one, you decide what button it gets (the key) and what snack pops out (the value). A dictionary comprehension is you setting up the whole machine in one breath: "for each fruit, button = name, snack = price." If you only care about a bag of distinct stickers and don't want repeats, that's a set — you just toss things in and any duplicate sticker is thrown away automatically.


Flashcards

What is the syntax of a dictionary comprehension?
{k_expr: v_expr for item in iterable if cond}
What is the syntax of a set comprehension?
{v_expr for item in iterable if cond}
What distinguishes a set comprehension from a dict comprehension syntactically?
The colon : between key and value (dict has it, set doesn't)
What does {} create in Python?
An empty dict (use set() for an empty set)
In {v: k for k, v in d.items()}, what happens?
It inverts the dict, swapping keys and values
What happens when two items produce the same key in a dict comprehension?
The later one overwrites the earlier (keys are unique)
What happens to duplicate values in a set comprehension?
They are dropped; sets keep only distinct elements
Where does a filtering if go in a comprehension?
At the end, after the for-clause
Where does an if/else value-chooser go?
In the value expression (front), as a ternary
Why are comprehensions often faster than loops?
The iteration runs in C internally, avoiding per-item Python bytecode overhead
Why must dict keys be hashable?
Dicts use hashing to store/look up keys; unhashable types like lists can't be keys

Connections

  • List comprehensions — same syntax family, produces a list with []
  • Dictionaries in Python — the data structure being built
  • Sets in Python — unordered unique collections
  • Generator expressions(...) lazy version, no materialised collection
  • Hashing and hashable types — why keys/elements must be hashable
  • Ternary conditional expression — used inside the value slot

Concept Map

uses

distinguished by

colon present

no colon

evaluates

evaluates

folded via

produces

produces

requires

guarantees

causes

Comprehension factory

Shared braces {}

Colon presence

Dict comprehension

Set comprehension

key:value pair

single value

Plain for loop

Translation rule

Empty {} is dict trap

Unique hashable keys

No duplicates

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, comprehension ka matlab hai ek chhoti si line mein poora collection bana dena. List comprehension toh tum jaante ho [...]. Bas waisa hi dict aur set comprehension hota hai, lekin yahan curly braces {} use hote hain. Sabse important baat: agar tum colon : lagate ho jaise {k: v for ...} toh wo dictionary banta hai (key aur value ka pair), aur agar colon nahi hai jaise {v for ...} toh wo set banta hai (sirf unique values, duplicates apne aap hat jaate hain).

Ek bada confusion: {} likhne se empty dict banta hai, empty set nahi! Empty set ke liye set() likhna padta hai — ye trap hamesha yaad rakhna. Aur dict mein keys hamesha unique hoti hain, toh agar do items same key banayein toh baad wala purane ko overwrite kar dega.

Derivation simple hai: pehle normal loop socho — empty dict banao, for chalaao, d[k] = v karo. Ab in teen lines ko ulta karke ek line mein daal do: {k: v for ...}. Bas wahi assignment aage aa gaya, loop peeche chala gaya. if condition agar last mein hai toh wo filter karti hai (kaun item andar aayega), aur agar if/else value wale part mein hai toh wo decide karti hai kya value rakhni hai. Ye cheezein interview aur real code dono mein bahut kaam aati hain kyunki clean aur fast dono hoti hain.

Go deeper — visual, from zero

Test yourself — Introduction to Programming (Python)

Connections