Basic Dictionary Comprehension Syntax
The syntax is: {key_expression: value_expression for item in iterable}.
Python
# Basic dict comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares)
# Equivalent for-loop (more verbose):
squares_loop = {}
for x in range(1, 6):
squares_loop[x] = x**2
βΆ Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Dict Comprehension with Filtering
Add an if condition to filter which items get included.
Python
numbers = range(1, 11)
# Only even numbers
even_squares = {x: x**2 for x in numbers if x % 2 == 0}
print(even_squares)
βΆ Output
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
Ad β 336Γ280
Transforming an Existing Dict
Apply transformations to keys or values of an existing dictionary.
Python
prices = {"apple": 1.50, "banana": 0.75, "cherry": 2.00}
# Apply 20% discount to all prices
discounted = {item: round(price * 0.8, 2) for item, price in prices.items()}
print(discounted)
# Make all keys uppercase
upper_prices = {k.upper(): v for k, v in prices.items()}
print(upper_prices)
βΆ Output
{'apple': 1.2, 'banana': 0.6, 'cherry': 1.6}
{'APPLE': 1.5, 'BANANA': 0.75, 'CHERRY': 2.0}
Inverting a Dictionary
Swap keys and values. Only works if values are unique and hashable.
Python
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted)
βΆ Output
{1: 'a', 2: 'b', 3: 'c'}
Building Dict from Two Lists
Use zip() to pair two lists into a dictionary.
Python
keys = ["name", "age", "city"]
values = ["Alice", 30, "London"]
result = {k: v for k, v in zip(keys, values)}
print(result)
# Or even simpler:
result2 = dict(zip(keys, values))
print(result2)
βΆ Output
{'name': 'Alice', 'age': 30, 'city': 'London'}
{'name': 'Alice', 'age': 30, 'city': 'London'}