Basic Dictionary Comprehension Syntax
The syntax is: {key_expression: value_expression for item in iterable}.
# 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
Dict Comprehension with Filtering
Add an if condition to filter which items get included.
numbers = range(1, 11)
# Only even numbers
even_squares = {x: x**2 for x in numbers if x % 2 == 0}
print(even_squares)
Transforming an Existing Dict
Apply transformations to keys or values of an existing dictionary.
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)
Inverting a Dictionary
Swap keys and values. Only works if values are unique and hashable.
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted)
Building Dict from Two Lists
Use zip() to pair two lists into a dictionary.
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)
Dict Comprehensions: Build Maps in One Expression
A dict comprehension creates a dictionary from an iterable in a single readable line — the same idea as a list comprehension, but producing key: value pairs.
nums = [1, 2, 3, 4]
squares = {n: n*n for n in nums} # {1: 1, 2: 4, 3: 9, 4: 16}
# filter while building
evens = {n: n*n for n in nums if n % 2 == 0} # {2: 4, 4: 16}
# invert a dict (swap keys and values)
inverted = {v: k for k, v in original.items()}
# build from two lists
dict(zip(keys, values)) # pairs them up
| Task | Comprehension |
|---|---|
| transform values | {k: f(v) for k, v in d.items()} |
| filter keys | {k: v for k, v in d.items() if cond} |
| invert | {v: k for k, v in d.items()} |
Two common uses: transforming an existing dict (apply a function to every value, or keep only some keys) and building a lookup table from data. Iterate with .items() to get key and value together. Gotchas: keys must be unique — if your expression produces the same key twice, the later value silently wins. And keys must be hashable, so inverting a dict only works if the values were hashable (no lists as values → keys). For simple key/value pairing from two sequences, dict(zip(keys, values)) is even shorter.
🏋️ Practical Exercise
Practice building dicts concisely:
- Create a dict mapping numbers 1–5 to their squares with a comprehension.
- Filter an existing prices dict to keep only items costing more than $10.
- Build a dict from two lists (names and scores) using
zip(). - Invert a dict so its values become keys and vice versa.
🔥 Challenge Exercise
Given a sentence, build a dictionary that counts how many times each word appears, using a dict comprehension over the unique words. Then create a second comprehension that keeps only the words appearing more than once, and a third that maps each word to its length. Bonus: normalize case and strip punctuation before counting.
📋 Summary
- A dict comprehension builds a dictionary in one expression:
{k: v for item in iterable}. - Add a filter with a trailing
if:{k: v for ... if condition}. - Pair two lists into a dict with
{k: v for k, v in zip(keys, values)}. - Invert a dict with
{v: k for k, v in d.items()}(assuming values are unique). - They are usually more concise and slightly faster than an equivalent
forloop. - Keep them readable — move complex logic into a loop or helper if a comprehension gets dense.
Interview Questions on Dictionary Comprehensions
- What is a dictionary comprehension and what is its syntax?
- How do you add a condition (filter) to a dict comprehension?
- How do you build a dictionary from two lists?
- How do you invert a dictionary using a comprehension?
- What is the difference between a dict comprehension and a list comprehension?
- Are dict comprehensions faster than building a dict in a loop?
- Can you nest dict comprehensions?
Related Topics
FAQ
A list comprehension uses square brackets and produces a list of single values. A dict comprehension uses curly braces and a key: value expression, producing key–value pairs. Otherwise the looping and filtering syntax is identical.
Usually a little faster, because the work happens in optimized C internally and avoids repeated dict[key] = value calls. The bigger benefit is readability for simple transformations.
Use {v: k for k, v in d.items()}. Be aware that if two keys share the same value, the inverted dict keeps only the last one, since dict keys must be unique.
Yes. Put the transformation in the key: value part and the filter in a trailing if, e.g. {k: v*2 for k, v in d.items() if v > 0}.

