Python Dictionary Comprehensions Explained
Build a dictionary in one line with Python's dict comprehension syntax {k: v for ...}, including filtering and inverting an existing dict.
Published September 17, 2026
A dictionary comprehension builds a dict in one expression: {key: value for item in iterable if condition}. It is the dict version of a list comprehension.
The concept
Instead of creating an empty dict and assigning keys in a loop, you declare the key and value expressions and let Python do the loop.
Duplicate keys overwrite earlier ones, so the last value for a key wins.
Build and transform
{n: n*n for n in range(4)}
{0: 0, 1: 1, 2: 4, 3: 9}
{v: k for k, v in {'a': 1, 'b': 2}.items()}
{1: 'a', 2: 'b'}
Practical examples
Filter a dict
prices = {'a': 5, 'b': 20, 'c': 12}
cheap = {k: v for k, v in prices.items() if v < 15}Count characters
s = 'banana'
counts = {ch: s.count(ch) for ch in set(s)}Zip two lists into a dict
keys = ['name', 'age']; vals = ['Ada', 36]
record = {k: v for k, v in zip(keys, vals)}Common mistakes
- Forgetting .items() when looping over key/value pairs.
- Using mutable values like lists as keys.
- Expecting duplicates to be kept.
Key takeaways
- {k: v for ...} builds dicts in one line.
- Use .items() for pairs.
- Last duplicate key wins.
FAQ
Can I add a condition?
Yes, append if condition at the end.
Is there a set comprehension?
Yes: {x for x in items}.