← Back to Python Course | Chapter 6: Data Structures | Lesson 9 of 12

Python Dict Comprehension

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

python
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

python
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

python
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

python
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

python
scores = {"Alex": 80, "Sam": 40}
results = {k: "pass" if v >= 50 else "fail" for k, v in scores.items()}
print(results)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.