Difficulty: Intermediate
Dictionary comprehensions provide a concise way to create dictionaries from iterables, similar to how list comprehensions create lists. The syntax is {key_expr: value_expr for item in iterable}, which evaluates the key and value expressions for each item and collects the results into a new dictionary. This is both more readable and more performant than building dictionaries with explicit loops.
Filtering is done by adding an if clause at the end: {k: v for k, v in dict.items() if condition}. This creates a new dictionary containing only the key-value pairs that satisfy the condition. You can filter on keys, values, or both. This pattern is extremely common for extracting subsets of data from larger dictionaries.
Transforming dictionaries involves applying functions to keys, values, or both. For example, {k: v * 2 for k, v in prices.items()} doubles all values, while {k.upper(): v for k, v in data.items()} uppercases all keys. You can combine filtering and transformation in a single comprehension for powerful one-liner data processing.
The zip() function paired with dict comprehensions is a common pattern for creating dictionaries from two parallel sequences. dict(zip(keys, values)) or {k: v for k, v in zip(keys, values)} pairs up elements from two iterables into key-value pairs. This is frequently used when you have column headers and row data, or when merging related lists.
Nested dictionary comprehensions are possible but should be used sparingly for readability. A comprehension like {outer_k: {inner_k: inner_v for ...} for ...} creates a dictionary of dictionaries. When the logic becomes complex, it is usually better to use a regular for loop for clarity.
# Squares of numbers
squares = {n: n 2 for n in range(1, 6)}
print('Squares:', squares)
# From a string: character -> ASCII code
word = 'hello'
ascii_map = {ch: ord(ch) for ch in word}
print('ASCII:', ascii_map)
# Swapping keys and values
original = {'a': 1, 'b': 2, 'c': 3}
swapped = {v: k for k, v in original.items()}
print('Swapped:', swapped)
Dict comprehensions use {key: value for item in iterable} syntax. Note that 'hello' has two l's but the dict keeps only one since keys must be unique. Swapping keys and values only works when all values are unique and hashable.
scores = {'Alice': 85, 'Bob': 62, 'Charlie': 91, 'Diana': 55, 'Eve': 78}
# Filter students who passed (>= 70)
passed = {name: score for name, score in scores.items() if score >= 70}
print('Passed:', passed)
# Filter students who failed
failed = {name: score for name, score in scores.items() if score < 70}
print('Failed:', failed)
# Filter and transform: grade labels
graded = {name: ('Distinction' if score >= 85 else 'Pass')
for name, score in scores.items() if score >= 70}
print('Graded:', graded)
Add an if clause after the for clause to filter. You can combine filtering (if) with value transformation (ternary expression) in a single comprehension. The filtering happens first, then the transformation is applied to the remaining items.
# Two parallel lists
cities = ['Mumbai', 'Delhi', 'Bangalore', 'Chennai']
populations = [20.4, 16.8, 12.3, 10.9]
city_pop = dict(zip(cities, populations))
print('Populations:', city_pop)
# With comprehension for transformation
city_pop_m = {city: f'{pop}M' for city, pop in zip(cities, populations)}
print('Formatted:', city_pop_m)
# Enumerate to create index mapping
fruits = ['apple', 'banana', 'cherry']
index_map = {fruit: idx for idx, fruit in enumerate(fruits)}
print('Index map:', index_map)
zip() pairs up elements from two sequences. dict(zip(...)) is the fastest way to create a dict from two lists. Using a comprehension with zip lets you transform values during creation. enumerate() provides indices alongside values.
prices = {'apple': 120, 'banana': 40, 'mango': 200, 'grape': 80}
# Apply 10% discount
discounted = {item: round(price * 0.9) for item, price in prices.items()}
print('Discounted:', discounted)
# Uppercase keys
upper_prices = {item.upper(): price for item, price in prices.items()}
print('Upper keys:', upper_prices)
# Categorize by price range
categorized = {item: ('premium' if price > 100 else 'regular')
for item, price in prices.items()}
print('Categories:', categorized)
Dict comprehensions can transform keys, values, or both. round() ensures clean numeric output. Ternary expressions in the value position let you categorize or label data on the fly.
dict comprehension, filtering dicts, transforming values, zip to dict, conditional comprehension