Python Dict Comprehension Syntax: A Practical Guide
Learn how to write and read Python dict comprehensions: basic syntax, filtering, nested dicts, common pitfalls, and how they compare with explicit loops.

Python dict comprehension syntax lets you build dictionaries from iterables in a single expression. It follows the same pattern as list comprehensions but produces a mapping instead of a sequence. For example, {x: x**2 for x in range(5)} creates {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}. This compact form is useful when you need to transform one collection into a dictionary without writing an explicit loop and accumulating values manually.
The Basic Syntax
The core syntax is straightforward:
{key_expression: value_expression for item in iterable}The key_expression and value_expression are evaluated for each item in the iterable. Both can reference the loop variable item, or any other variable in scope. Here is a minimal example that maps strings to their lengths:
words = ["apple", "banana", "cherry"]
lengths = {word: len(word) for word in words}
# {'apple': 5, 'banana': 6, 'cherry': 6}This replaces the more verbose loop:
lengths = {}
for word in words:
lengths[word] = len(word)The comprehension version is more readable because the intent is declared directly: a dictionary where each key is a word and each value is its length.
Adding Conditions with if and else
You can filter items with an if clause at the end of the comprehension. This excludes items that do not satisfy the condition:
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}The if clause only controls which items are included; it does not change the key or value expressions. If you need to produce different values based on a condition, use a conditional expression in the value (or key) position:
parity = {x: "even" if x % 2 == 0 else "odd" for x in range(5)}
# {0: 'even', 1: 'odd', 2: 'even', 3: 'odd', 4: 'even'}This is equivalent to writing an if-else inside the loop body. An if filter must come after the for clause, and multiple if filters are allowed and behave like an and condition.
Nested Dict Comprehensions
Dict comprehensions can use multiple for clauses to iterate over nested structures. This is useful for building dictionaries of dictionaries. For example, to create a multiplication table as a nested dict:
table = {i: {j: i * j for j in range(1, 6)} for i in range(1, 6)}The outer comprehension iterates over i, and for each i, the inner comprehension builds a dictionary mapping j to i * j. The result is a 5x5 table. Nested comprehensions can become hard to read if they go deeper than two levels. In such cases, a regular loop with explicit variable names is often clearer.
Using enumerate, zip, and Other Iterables
Dict comprehensions work with any iterable, including those produced by built-in functions. A common pattern is to build a dictionary from an enumerated list, using the index as the key:
colors = ["red", "green", "blue"]
color_map = {i: color for i, color in enumerate(colors)}
# {0: 'red', 1: 'green', 2: 'blue'}Similarly, zip lets you combine two sequences into key-value pairs:
keys = ["name", "age", "city"]
values = ["Alice", 30, "New York"]
person = {k: v for k, v in zip(keys, values)}
# {'name': 'Alice', 'age': 30, 'city': 'New York'}You can also use dictionary methods like .items() on an existing dict to transform it:
original = {"a": 1, "b": 2}
inverted = {v: k for k, v in original.items()}
# {1: 'a', 2: 'b'}This is a concise way to swap keys and values, but be aware that if the original values are not unique, later keys will overwrite earlier ones.
Performance and Memory Considerations
Dict comprehensions are not inherently faster than an explicit loop. They are a syntactic convenience that often improves readability, and the runtime generally performs the same number of iterations and assignments. Small performance differences are possible, but choose a comprehension or a loop based on clarity unless profiling shows a real bottleneck. For large iterables, the comprehension builds the entire dictionary in memory at once, just like a loop would. If you are generating pairs from a stream, a generator expression passed to dict() can avoid building an intermediate list of pairs:
dict((x, x**2) for x in range(1000000))This passes a generator to dict, which consumes items lazily. The resulting dictionary still holds all key-value pairs, so overall memory for the dictionary is the same as with a comprehension. The real tradeoff is between readability and the need for early termination or side effects. If you need to break out of the loop based on a complex condition, a regular for loop is more flexible.
Common Mistakes and How to Avoid Them
One frequent mistake is assuming that the if clause can be placed before the for clause. The correct order is {key: value for item in iterable if condition}. Putting if earlier results in a syntax error.
Another issue is key collisions. If the key expression produces duplicate keys, the last value wins silently. This can hide bugs when transforming data with non-unique keys. For example:
data = [("a", 1), ("a", 2)]
result = {k: v for k, v in data}
# {'a': 2}If you expect to keep all values, you need to aggregate them manually or use a defaultdict.
Finally, be careful with mutable values. A literal like [] is evaluated fresh on each iteration, so {x: [] for x in range(3)} creates three separate lists. If you reuse a single list or dict as the value, all entries will reference the same mutable object, and changes will be shared.
When to Use Regular Loops Instead
Dict comprehensions are best for simple transformations that fit on one line and do not require complex control flow. Use a regular loop when you need to:
- Update an existing dictionary in place.
- Perform multiple operations per item that are not easily expressed in a single expression.
- Break out of the loop early based on a condition.
- Log or debug each iteration.
- Build a dictionary incrementally over a long-running process.
A regular loop also makes it easier to add comments or handle exceptions per item. For example, if a value conversion might raise an exception and you need to skip that item, a comprehension cannot catch the exception without a helper function. In that case, a loop with try-except is clearer.
result = {}
for key, value in raw_data:
try:
result[key] = int(value)
except ValueError:
continueThis is more maintainable than trying to force the same logic into a comprehension. The dict comprehension syntax is a powerful tool, but it is not always the right one. Choose it when the mapping is straightforward and the comprehension reads naturally; choose a loop when the logic needs more room to express itself.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.