1.2.35 · Coding › Introduction to Programming (Python)
Ek comprehension ek factory hai jo poori collection ko ek hi expression mein build karta hai. Tum list comprehensions ko jaante ho jo lists [...] banate hain. Dictionary aur set comprehensions same idea hai lekin yeh ek dict {k: v ...} ya set {v ...} produce karte hain. Braces {} shared hain, aur colon : ki presence hi Python ko batati hai "yeh ek dict hai, set nahi."
Definition Dictionary comprehension
Ek compact expression jo ek dictionary banata hai har iterable ke item ke liye ek key:value pair evaluate karke:
{ key_expr : value_expr for item in iterable [if cond] }
Result ek dict hota hai, isliye keys unique aur hashable honi chahiye .
Definition Set comprehension
Ek compact expression jo ek set (unordered, no duplicates) banata hai har item ke liye ek value evaluate karke:
{ value_expr for item in iterable [if cond] }
Colon nahi ⇒ set. Duplicates automatically drop ho jaate hain.
Common mistake The empty-braces trap (steel-man)
{} lagta hai jaise ek empty set ho kyunki {1,2,3} ek set hai. Lekin {} ek empty dict hai — historically dicts ko pehle braces mile. Fix yeh hai: empty set ke liye set() use karo.
type({}) → dict, type(set()) → set.
WHY: Ek dict/set ko for loop se banana 3–4 lines leta hai (empty create karo, loop karo, d[k]=v).
Comprehensions intent ko ("har x ke liye yeh pair banao") ek readable line mein express karte hain, aur yeh faster chalte hain kyunki looping C mein hoti hai, na ki har .append par interpreted Python bytecode mein.
Loop version aur comprehension version logically identical hain. Chaliye ise derive karte hain.
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 )}
Worked example 1 — Number → its square
{n: n ** 2 for n in range ( 1 , 6 )}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Yeh step kyun? n key hai (jisse hum lookup karte hain), n**2 value hai (jo hume wापस milti hai).
Reading order: pehle value-rule, phir source — jaise kehna "har n ke liye mujhe n² do."
Worked example 2 — Filter with
if
{n: n ** 2 for n in range ( 1 , 11 ) if n % 2 == 0 }
# {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
Yeh step kyun? if pair build hone se pehle run hota hai, isliye sirf even n hi entry create karta hai. Condition select karti hai kaun se items andar jaate hain .
Worked example 3 — Invert a dictionary (swap keys/values)
grades = { "Asha" : 90 , "Ravi" : 75 }
{v: k for k, v in grades.items()}
# {90: 'Asha', 75: 'Ravi'}
Yeh step kyun? .items() (key, value) tuples yield karta hai; hum k, v mein unpack karte hain aur v ko naya key banate hain. Caveat: agar do students ka same grade hota, toh ek doosre ko overwrite kar deta (keys unique hoti hain).
Worked example 4 — Set comprehension: unique word lengths
words = [ "cat" , "dog" , "tiger" , "ox" ]
{ len (w) for w in words}
# {2, 3, 5} ('cat' and 'dog' dono 3 dete hain, ek baar rakha jaata hai)
Yeh step kyun? Colon nahi ⇒ set. Duplicate length 3 silently collapse ho jaati hai — set use karne ka poora point yahi hai.
dict with conditional value (if/else goes in the value )
{n: ( "even" if n % 2 == 0 else "odd" ) for n in range ( 4 )}
# {0: 'even', 1: 'odd', 2: 'even', 3: 'odd'}
Yeh step kyun? Ek filtering if end mein hota hai; ek value-choosing if/else ek ternary hai jo front mein value expression mein hota hai. Alag kaam, alag positions.
Common mistake Common errors (steel-man + fix)
(a) Set vs dict confusion. {x for x in data} lagta hai jaise cheezein pair karni chahiye — braces ki wajah se dict jaisa feel hota hai. Fix: colon nahi = set; colon k:v = dict.
(b) Keys overwrite karna bhool jaana. {x % 3: x for x in range(6)} mein tum expect karte ho 6 entries lekin milte hain 3 — baad ke items pehle walon ko overwrite karte hain jo same key share karte hain. Fix: agar sabko rakhna hai, toh list value mein group karo.
(c) Unhashable keys. {[1,2]: "a" for ...} crash karta hai; lists keys nahi ban sakti. Fix: tuple use karo.
Recall Active recall — cover the answers
Kaun sa single character ek dict comprehension ko set comprehension se alag karta hai? → ==colon :==
{} kya evaluate hota hai? → ek empty dict
Ek filter if kahan jaata hai vs ek if/else value chooser ? → filter end mein; ternary value/front mein
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.
"COLON = DICT, NO COLON = SET; BRACES-ALONE = DICT."
Ya: "Do dots ek deal banate hain (key:value)."
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
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