Python Dict Comprehension
In this page:
Basic Dict Comprehension
Dictionary comprehensions build a new dict in one expression using {key_expr: value_expr for item in iterable}, which is the dict equivalent of a list comprehension and is typically faster and more readable than looping with an empty dict and repeated assignment.
Example: Basic Dict Comprehension
nums = [1, 2, 3]
squares = {n: n * n for n in nums}
print(squares)
Filtering with If-Conditions
Adding 'if condition' at the end filters which source items get turned into entries -- {k: v for k, v in pairs if v > 0} keeps only the pairs whose value is positive, discarding the rest entirely rather than transforming them.
Example: Filtering with If-Conditions
pairs = {"a": 1, "b": -2, "c": 3}
positive = {k: v for k, v in pairs.items() if v > 0}
print(positive)
Transforming Keys and Values
You can compute both the key and the value from the same source item, letting you reshape data as you go -- for example {name.lower(): len(name) for name in names} both normalizes the key and derives a new value in a single pass.
Example: Transforming Keys and Values
names = ["Alice", "Bob"]
lengths = {name.lower(): len(name) for name in names}
print(lengths)
Creating Dict from Two Lists
zip() pairs up two same-length lists element by element, and wrapping that in a comprehension -- {k: v for k, v in zip(keys, values)} -- turns two parallel lists into a single dictionary without a manual loop.
Example: Creating Dict from Two Lists
keys = ["a", "b", "c"]
values = [1, 2, 3]
combined = {k: v for k, v in zip(keys, values)}
print(combined)
Comprehension with If-Else Conditions
Placing a ternary if-else before the for clause lets every key get a value based on a condition rather than being excluded -- {k: pass if v >= 50 else fail for k, v in scores.items()} keeps every key while varying its mapped value.
Example: Comprehension with If-Else Conditions
scores = {"Alex": 80, "Sam": 40}
results = {k: "pass" if v >= 50 else "fail" for k, v in scores.items()}
print(results)
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: