1.2.35 · D3 · HinglishIntroduction to Programming (Python)

Worked examplesDictionary and set comprehensions

4,763 words22 min read↑ Read in English

1.2.35 · D3 · Coding › Introduction to Programming (Python) › Dictionary and set comprehensions

Yeh page sirf wahi assume karta hai jo parent note ne build kiya. Agar koi term naya lagta hai, use yahan dobara earn kiya jayega.


The scenario matrix

Har comprehension question actually is table ki ek row hai. Har cell ek alag behaviour hai jise tumhe sight par predict kar paana chahiye.

# Case class Kya mushkil banata hai isse Example jo isko hit karta hai
A Basic dict, unique keys kuch nahi — yeh baseline hai Ex 1
B Key collision (do items, same key) baad wali value overwrite karti hai Ex 2
C Collision fixed by grouping into lists sab kuch rakho Ex 3
D Filter if at the end kuch items koi entry produce nahi karte Ex 4
E Ternary if/else in the value har 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 (do fors) Cartesian sweep Ex 8
I Unhashable key — crash ka case list key nahi ban sakti Ex 9
J Real-world word problem + exam twist syntax mein intent padhna Ex 10
K Chained filters (if cond1 if cond2) dono pass hone chahiye Ex 11

Neeche Figure s01 dekho: yeh ek comprehension ke teen parts ko exact us order mein label karta hai jisme tumhe padhne chahiye — black arrows for (part 1) aur if (part 2) ki taraf point karte hain, aur red arrow colon wale head (part 3) ko highlight karta hai, woh piece jo dict-vs-set decide karta hai. Koi bhi real code padhne se pehle numbered order mein arrows trace karo.

Figure — Dictionary and set comprehensions

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


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

Neeche Figure s02 dekho: top par chhe input boxes (x=0..5) teen key buckets mein fan down hote hain. Chhe thin black arrows land karte, lekin sirf red arrows — har bucket mein last write — bachte hain, aur buckets ke neeche red -> 3 / -> 4 / -> 5 final stored value hai. Yeh picture wahi hai "last write wins" rule visible banaya hua.

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)

Neeche Figure s03 dekho: 3×3 grid har (i, j) combination ko ek dot ke roop mein dikhata hai, saath mein choti si product i*j likhi hui — i vertical axis par chadhta hai (outer loop), j horizontal par chalta hai (inner loop). Red dot key (2, 3) mark karta hai, jiska stored value 6 hai, toh tum dekh sakte ho ki nested fors ek rectangle of keys enumerate karte hain.

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)


Matrix ko wapas jodna

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 — answers chhupa lo

{x % 3: x for x in range(6)} kitni entries produce karta hai? ::: 3 — keys 0,1,2, har ek apni last value 3,4,5 ke saath Woh keys kis order mein print honti hain, aur kyun? ::: 0, 1, 2 — unka first-insertion order (dicts Python 3.7 ke baad se insertion order preserve karte hain) Overwrite karne ki jagah saare colliding items kaise rakhe jaayein? ::: List values mein accumulate karo (e.g. defaultdict(list)), phir dict mein snapshot lo Trailing if vs value-ternary — kaun items drop karta hai? ::: Trailing if items drop karta hai; ternary sab rakhta hai aur sirf values change karta hai {len(w) for w in ["hi","cat","dog"]} kya deta hai? ::: {2, 3} — duplicate length 3 collapse ho jaata hai {k: v for k, v in []} kya return karta hai, aur kis type ka? ::: {}, ek empty dict (syntax mein colon hai) {[i]: i for i in range(3)} crash kyun karta hai? ::: Ek list unhashable hai (mutable), toh woh dict key nahi ban sakti Ek comprehension mein back-to-back do ifs ka matlab kya hai? ::: AND — ek item ko dono conditions pass karni hongi Names-ka-set ko names→0-ka-dict mein badalne ke liye kya single edit chahiye? ::: Colon aur ek value add karo: {name: 0 for ...} Python mein ** ka matlab kya hai? ::: Power (exponent) operator — n**2 hai , n**3 hai


Connections

  • Parent: Dictionary and set comprehensions — woh core rules jinhe yeh page stress-test karta hai
  • List comprehensions — same syntax family with []
  • Dictionaries in Python — collision / last-write-wins behaviour aur insertion order
  • Sets in Python — Example 6 mein automatic uniqueness
  • Generator expressions — lazy (...) cousin, koi collision handling nahi kyunki kuch store nahi hota
  • Hashing and hashable types — kyun Example 9 crash karta hai aur "hashable" ka matlab kya hai
  • Ternary conditional expression — Example 5 mein value-chooser