1.2.35 · D1 · HinglishIntroduction to Programming (Python)

FoundationsDictionary and set comprehensions

3,044 words14 min read↑ Read in English

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

Yeh page assume karta hai ki tumne {n: n ** 2 for n in range(5)} kabhi nahi dekha. Hum iska koi piece tab tak use nahi karenge jab tak us piece ka plain-words meaning AUR ek picture na ho. End tak, parent note ordinary English ki tarah padhega.


Atoms, build-order mein

Hum sabse basic idea (ek collection) se full comprehension tak jaate hain. Har step sirf wahi reuse karta hai jo pehle aaya.

1. Ek collection = ek container jo kaafi saari cheezein hold karta hai

Picture: ek row of egg-cups imagine karo. Har cup ek value hold karta hai; poori tray ka ek naam hota hai.

Yeh topic ko kyun chahiye: comprehensions collections produce karte hain. Agar tum "cheezein ka ek box" picture nahi karte, toh "builds a whole collection in one expression" phrase ka koi matlab nahi.


2. Square brackets [ ] = ek list (ordered, duplicates allowed)

  • Ordered = ek first, ek second, ek third hota hai; tum pooch sakte ho "position 0 par kya hai?"
  • Duplicates allowed = same value do baar appear ho sakti hai.

Yeh topic ko kyun chahiye: parent kehta hai "tum pehle se list comprehensions jaante ho." Lists starting shape hain. Dict aur set comprehensions ko "same idea but different braces" describe kiya jaata hai, isliye pehle tumhe list version ka matlab pata hona chahiye.


3. Power operator ** = "kisi power par raise karo"

Humare pehle preview line ne n ** 2 kaha tha. Us symbol ko unexplained na chhoden.

Yeh topic ko kyun chahiye: parent ke examples 1 aur 2 values n ** 2 aur n**2 se build karte hain. Woh comprehension ki value-rule hai — operator miss karo aur har output galat lagega.


4. Curly braces { } = dict AUR set ke shared brackets

Yeh thought hold karo: { } akele ambiguous hai jab tak tum ek chhoti si mark nahi dhoondh lete. Woh mark hai colon (agle step mein).

Yeh topic ko kyun chahiye: poora parent page { } mein likha hai. Uska headline claim ("braces {} shared hain, aur colon : ki presence dict-vs-set decide karti hai") bilkul isi overloading ke baare mein hai — isliye tumhe pata hona chahiye ki braces double duty karte hain pehle us sentence ka koi matlab bane.


5. Colon : = "is key ko us value ke saath pair karta hai"

Yeh poore parent page par sabse important symbol hai, isliye hum ise carefully build karte hain.

Picture: ek two-column table. Left column = keys (labels). Right column = values (payloads). Colon har row mein arrow hai.

  • { "cat": 3 } — colon → ek dictionary (ek labelled lookup table).
  • { "cat", 3 } — no colon, sirf values commas se separated → ek set.

Yeh topic ko kyun chahiye: parent ka headline claim hai "colon : ki presence hi Python ko batati hai ki yeh ek dict hai, set nahi." Tum us claim ko verify nahi kar sakte jab tak tumhe pata na ho ki key:value pair kya hota hai.

Full data structure ke liye Dictionaries in Python aur no-duplicates box ke liye Sets in Python dekho.


6. Ek set = distinct cheezein ka ek bag, koi order nahi

Picture: stickers ka ek drawstring bag. Do identical stickers drop karo aur tumhare paas phir bhi sirf ek hoga — bag copies refuse karta hai.

Yeh topic ko kyun chahiye: set comprehensions isliye exist karte hain kyunki yeh auto-dedup useful hai (example 4: unique word lengths). "Duplicates vanish ho jaate hain" picture kiye bina, set comprehension ka point kho jaata hai.


7. Ek tuple ( ) = comma-separated values ki ek fixed row

Picture: ek stapled index card jisme fixed number of blanks pehle se fill hain — tum har blank padh sakte ho, lekin naya add nahi kar sakte.

Yeh topic ko kyun chahiye: d.items() (step 12) har row tuple (key, value) ke roop mein wapas deta hai, aur parent ki mistake (c) fix — "compound key ke liye tuple use karo" — is par depend karti hai ki tum jaante ho tuple kya hai.


8. Iterable = kuch bhi jise tum ek ek item karke walk through kar sako

Picture: ek conveyor belt. Items ek ek karke tumhare paas se guzarte hain, aur aate hi process ho jaate hain.

Yeh topic ko kyun chahiye: har comprehension ki shape ... for item in ITERABLE ... hoti hai. Iterable woh conveyor belt hai jo poori factory ko drive karta hai.


9. range(n) = counting conveyor 0, 1, 2, …, n−1

Yeh topic ko kyun chahiye: almost har worked example ek range(...) par loop karta hai. Agar tum uska output galat count karo, toh har result galat lagega.


10. for item in iterable = "har item ko, baari baari, lo"

Picture: conveyor belt phir se, lekin ab ek chhoti tag jis par n likha hai woh whichever box currently tumhare saamne ho use clip ho jaati hai.

Yeh topic ko kyun chahiye: yeh har comprehension ki "tail" hai — engine. Parent ka mechanical rule is clause ko one-liner ke back mein move karta hai literally.


11. if condition = ek gate jo sirf kuch items ko through karne deta hai

  • % remainder operator hai: 10 % 3 hai 1 (10 = 3·3 + 1). n % 2 == 0 poochta hai "kya 2 se divide karne par remainder 0 hai?" → "kya n even hai?".
  • == equality test hai (True/False return karta hai), nahi = jo assign karta hai. Do bilkul alag symbols hain.

Picture: conveyor par ek turnstile. Even boxes pass hote hain; odd boxes reject ho jaate hain.

Yeh topic ko kyun chahiye: parent ka example 2 if n % 2 == 0 se filter karta hai. = (assign) aur == (test) ko confuse karna ek classic crash hai, isliye hum unhe abhi alag kar lete hain.


12. Ternary A if cond else B = ek value-chooser (filter NAHI)

Full treatment ke liye Ternary conditional expression dekho.

Yeh topic ko kyun chahiye: parent ka example 5 value slot mein if/else rakhta hai. Use filtering if ke saath mix up karna ek top confusion hai — apna atom worth karta hai.


13. .items() aur tuple unpacking for k, v in ...

Picture: step 5 ki two-column table, ek ek row padhi ja rahi hai — left cell k mein jaati hai, right cell v mein.

Yeh topic ko kyun chahiye: parent ka example 3 {v: k for k, v in grades.items()} se ek dict invert karta hai. .items() aur k, v unpacking dono pehle samajh aane chahiye.


14. Hashable = "key ke roop mein use ho sakta hai / set mein daala ja sakta hai"

Yeh topic ko kyun chahiye: dict keys aur set elements hashable honi chahiye. Parent ki mistake (c) — {[1,2]: "a" ...} crash karta hai — bilkul yahi rule hai. Hashing and hashable types dekho.


Atoms ko saath jodna: full skeleton

Ab jab har symbol ka ek meaning hai, unhe ek shape mein snap karo. Ek dict comprehension chaar slots ki hoti hai:

Ise left se right plain English mein padho: "Yeh key:value pair banao, iterable se aane wale har var ke liye, lekin sirf tab jab gate pass kare." Colon aur key slot drop karo, aur bilkul wahi skeleton ek set ban jaata hai:

Running preview {n: n ** 2 for n in range(5)} ko chaar slots mein trace karo:

  • key_expr = n → number se lookup karo.
  • value_expr = n ** 2 → uska square store karo.
  • for n in range(5) → conveyor 0,1,2,3,4 deta hai.
  • (koi if nahi) → har item pass hota hai.

Result: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}.


Duplicate-key gotcha

Ek edge case pehli baar sabko bite karta hai. Ek dict comprehension mein, keys unique honi chahiye — toh kya hota hai agar do items same key produce karein?

Ek set comprehension mein mirror-image behaviour hota hai: duplicate values bhi collapse ho jaati hain, lekin wahan tum yahi chahte ho (yahi toh poora point hai). Same "keep-one" rule, opposite intent.


Equipment checklist

Right side cover karo aur khud test karo — tum parent note ke liye tabhi ready ho jab har line instant ho.

A collection is…
ek box/naam jo ek saath kaafi saari values hold karta hai
[ ] builds a…
list — ordered, duplicates allowed
** means…
kisi power par raise karna; n ** 2 hai n × n, 2 ** 3 hai 8
Difference between * and **
* multiply karta hai (3*2=6); ** exponent hai (3**2=9)
{ } are the brackets shared by…
dono dictionaries aur sets
The single mark that makes braces a dict not a set
colon :
A key vs a value is…
key = jisse lookup karo; value = jo wapas milta hai
A set is…
ek unordered box jo automatically duplicates drop karta hai
{} (empty braces) creates a…
ek empty dict (empty set ke liye set() use karo)
A tuple is…
ek fixed-length, comma-separated group jaise (90, "Asha") — hashable
An iterable is…
kuch bhi jise tum ek ek item karke walk through kar sako
range(5) produces…
0, 1, 2, 3, 4 (stop excluded hai, 0 se start)
for n in range(5) does what to n
har item ko baari baari naam deta hai — n = 0, phir 1, phir 2…
n % 2 == 0 asks…
kya n even hai? (% = remainder, == = equality test)
Difference between = and ==
= ek naam assign karta hai; == equality test karta hai (True/False)
A filtering if goes…
end mein, decide karta hai ki ek item appear hoga ki nahi
A ternary A if cond else B goes…
value/front mein, decide karta hai ki item ko kya value milegi
d.items() yields…
har row ko (key, value) tuple ke roop mein
for k, v in d.items() does…
har tuple ko ek saath k aur v mein unpack karta hai
Hashable means…
fixed fingerprint hai → key ya set element ban sakta hai (lists nahi ban sakti)
Two items make the same dict key → …
baad wala jeet jaata hai; pehla silently overwrite ho jaata hai

Connections

  • ← parent topic par wapas
  • List comprehensions — woh [] sibling jis par tum build karte ho
  • Dictionaries in Python — labelled lookup table
  • Sets in Python — no-duplicates bag
  • Generator expressions — lazy () cousin
  • Hashing and hashable types — keys hashable kyun honi chahiye
  • Ternary conditional expression — value-chooser if/else