Python Dictionary Comprehension
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Dictionary comprehension is a concise syntax for creating dictionaries in Python, analogous to list comprehension for lists. Instead of writing multi-line loops to build a dictionary, you express the key-value mapping in a single expression. It is faster than equivalent for loops, more readable for simple transformations, and widely used for filtering, transforming, and inverting dictionaries.
Basic Syntax
This is equivalent to:
From Two Lists (zip)
Create a dictionary by pairing elements from two lists:
Filtering with Conditions
Add an if clause to include only items that meet a condition:
Transforming Keys or Values
Inverting a Dictionary
Swap keys and values:
If multiple keys map to the same value, the last one wins:
Nested Dictionary Comprehension
Create dictionaries of dictionaries:
Conditional Expressions (if-else)
Use a ternary expression in the value (not a filter):
Note the difference: if after the for filters items out, while if-else in the value expression transforms every item.
From enumerate
Performance: Comprehension vs Loop
Dictionary comprehension is generally 10-30% faster than equivalent for loops because the iteration happens in C-optimized code:
Common Pitfalls
- Duplicate keys silently overwrite: If the key expression produces duplicate keys, later values silently replace earlier ones. There is no error or warning. Use a list of tuples or
defaultdict(list)if you need to preserve all values. - Readability vs cleverness: Comprehensions with multiple conditions, nested loops, and complex expressions become harder to read than explicit loops. If the comprehension exceeds one line, consider a regular loop.
- Side effects: Dictionary comprehensions should not have side effects (like modifying external variables). Use a loop instead if you need side effects.
- Memory with large datasets: A comprehension creates the entire dictionary in memory at once. For very large datasets, consider using a generator with
dict()or processing items lazily. - Key must be hashable: Dictionary keys must be immutable and hashable (strings, numbers, tuples of hashable items). Using lists or dicts as keys raises
TypeError.
Summary
- Basic syntax:
{key: value for item in iterable} - Add
if conditionafter theforclause to filter items - Use
zip(keys, values)to create dicts from two parallel lists - Use
{v: k for k, v in d.items()}to invert a dictionary - Comprehensions are faster than equivalent
forloops for building dictionaries - Keep comprehensions simple — use loops for complex logic with multiple conditions
Related reading
- Python dictionary from an object's fields
- Python Dijkstra k shortest paths
- Python extend for a dictionary
- Python FastAPI building a single-threaded queue of jobs after API call
- Python implementation of Multiple-Choice Knapsack
- Python Implementations of Packing Algorithm
- python divide by zero encountered in log - logistic regression
- python efficient substring search

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.