How do dictionary and set comprehensions work in Python?
A dict comprehension uses curly braces with key: value, as in {k: v for ...}. A set comprehension uses curly braces with one expression, as in {x for ...}, and removes duplicates automatically.
Explain it simply
A list comprehension gives you a numbered queue. Swap the square brackets for curly braces and you get other containers. With a key: value pair you get a dictionary, like building a roll number to name register from two columns. With a single value you get a set, like a unique list of cities from a list of student addresses.
Example
names = ["Asha", "Dev", "Ira"]
lengths = {n: len(n) for n in names}
print(lengths) # Output: {'Asha': 4, 'Dev': 3, 'Ira': 3}
flipped = {v: k for k, v in {"a": 1, "b": 2}.items()}
print(flipped) # Output: {1: 'a', 2: 'b'}
cities = ["Pune", "Delhi", "Pune", "Delhi", "Ranchi"]
unique = {c.lower() for c in cities}
print(sorted(unique)) # Output: ['delhi', 'pune', 'ranchi']
big = {k: v for k, v in lengths.items() if v > 3}
print(big) # Output: {'Asha': 4}What to say in the interview
"Dict comprehensions are {key_expr: value_expr for x in iterable if cond}, and set comprehensions are {expr for x in iterable}. Sets drop duplicates. When inverting a dictionary, duplicate values collide and the later key wins, so I check for that."
Common mistakes
- Writing
{}expecting an empty set; it is an empty dict. - Inverting a dictionary whose values are not unique and silently losing keys.