1.2.35 · HinglishIntroduction to Programming (Python)

Dictionary and set comprehensions

1,526 words7 min readRead in English

1.2.35 · Coding › Introduction to Programming (Python)


WHAT are they?


WHY do they exist?

Loop version aur comprehension version logically identical hain. Chaliye ise derive karte hain.


HOW: derive the comprehension from a plain loop

Sabse basic, undeniable tarike se start karo dict banana — ek explicit loop:

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

Yeh kyun kaam karta hai: har pass mein ek key n ko value n*n assign hoti hai. Ab un teen lines ko ek expression mein fold karo — assignment target ko front mein aur loop ko back mein le jaao:

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

Worked examples



Recall Feynman: explain to a 12-year-old

Ek aisi vending machine imagine karo jo tum khud banaate ho. Tum items ki list se neeche jaate ho aur, har ek ke liye, decide karte ho kaunsa button use milega (key) aur kaun sa snack bahar aayega (value). Ek dictionary comprehension hai tum ek hi saansh mein poori machine setup kar rahe ho: "har fruit ke liye, button = naam, snack = price." Agar tum sirf alag stickers ka ek bag chahte ho aur repeats nahi chahte, toh woh ek set hai — tum bas cheezein andar daalo aur koi bhi duplicate sticker automatically phek diya jaata hai.


Flashcards

Dictionary comprehension ka syntax kya hai?
{k_expr: v_expr for item in iterable if cond}
Set comprehension ka syntax kya hai?
{v_expr for item in iterable if cond}
Set comprehension ko dict comprehension se syntactically kya alag karta hai?
Key aur value ke beech colon : (dict mein hota hai, set mein nahi)
{} Python mein kya create karta hai?
Ek empty dict (empty set ke liye set() use karo)
{v: k for k, v in d.items()} mein kya hota hai?
Yeh dict ko invert karta hai, keys aur values swap karke
Jab dict comprehension mein do items same key produce karein toh kya hota hai?
Baad wala pehle wale ko overwrite kar deta hai (keys unique hoti hain)
Set comprehension mein duplicate values ka kya hota hai?
Woh drop ho jaate hain; sets sirf distinct elements rakhte hain
Comprehension mein filtering if kahan jaata hai?
End mein, for-clause ke baad
if/else value-chooser kahan jaata hai?
Value expression (front) mein, ek ternary ke roop mein
Comprehensions loops se often faster kyun hote hain?
Iteration internally C mein run hoti hai, har item ke Python bytecode overhead se bachte hue
Dict keys hashable kyun honi chahiye?
Dicts keys store/look up karne ke liye hashing use karte hain; lists jaisi unhashable types keys nahi ban sakti

Connections

  • List comprehensions — same syntax family, [] se list produce karta hai
  • Dictionaries in Python — woh data structure jo build ho raha hai
  • Sets in Python — unordered unique collections
  • Generator expressions(...) lazy version, koi materialised collection nahi
  • Hashing and hashable types — kyun keys/elements hashable hone chahiye
  • Ternary conditional expression — value slot ke andar use hota hai

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