Start with the most basic, undeniable way to build a dict — an explicit loop:
squares = {} # 1. empty dictfor 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:
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.
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.