Python Dictionary Comprehension Condition
Learn how to apply conditions in Python dictionary comprehensions to filter entries, transform values, and avoid common mistakes.

A Python dictionary comprehension can include an optional if clause to filter items while building a dictionary. The general form is:
{key_expr: value_expr for item in iterable if condition}
For each item, the condition is evaluated; only items for which it is true produce a key-value pair in the resulting dictionary. This lets you filter and transform data directly, without a separate loop or an intermediate data structure.
Basic Filtering with an if Clause
Consider a list of tuples where each tuple contains a name and a score. You want a dictionary that maps names to scores only for scores above a threshold.
scores = [('alice', 82), ('bob', 74), ('carol', 91), ('dave', 68)]
passed = {name: score for name, score in scores if score >= 75}
print(passed) # {'alice': 82, 'carol': 91}The condition score >= 75 is evaluated for each tuple. When it is True, the tuple's name and score become a key-value pair. This is equivalent to a loop that checks the condition and inserts into a dictionary, but the comprehension is more concise and keeps the logic in one place.
Transforming Values with if-else
Sometimes you want to include every key but apply a different value depending on a condition. Use a conditional expression (ternary) inside the value expression.
words = ['apple', 'banana', 'cherry', 'date']
length_label = {word: ('long' if len(word) > 5 else 'short') for word in words}
print(length_label)
# {'apple': 'short', 'banana': 'long', 'cherry': 'long', 'date': 'short'}The ternary 'long' if len(word) > 5 else 'short' is evaluated for each word. This pattern is useful when you need to keep all keys but vary the stored value based on a rule. Note that the if clause and the ternary serve different purposes: the if clause filters which items are included, while the ternary changes the value for every included item.
Combining Multiple Conditions
You can use and, or, and parentheses to build complex filter logic. For example, keep entries where the key starts with a certain prefix and the value meets a numeric threshold.
inventory = {'apple': 12, 'apricot': 4, 'banana': 7, 'avocado': 9}
selected = {k: v for k, v in inventory.items() if k.startswith('a') and v > 5}
print(selected) # {'apple': 12, 'avocado': 9}Multiple conditions are evaluated left to right, and short-circuiting applies just as in ordinary boolean expressions. This keeps the comprehension readable without forcing you to precompute a separate list of filtered keys.
Performance and Memory Considerations
A dictionary comprehension builds the result directly and can be more concise than an equivalent explicit loop. It also avoids creating an intermediate filtered list. However, condition expressions are still ordinary Python code, so expensive function calls or repeated lookups inside the condition can dominate runtime. If the same lookup or computation is needed for many items, prepare it once before the comprehension.
allowed = {'apple', 'banana', 'cherry'}
data = {'apple': 1, 'banana': 2, 'cherry': 3, 'date': 4}
result = {k: v for k, v in data.items() if k in allowed}
print(result) # {'apple': 1, 'banana': 2, 'cherry': 3}Here allowed is a set, so membership tests are O(1). If data has m items and allowed were a list of n items, the in check would be O(n) for each item, making the comprehension O(n*m). The comprehension syntax itself does not change algorithmic complexity; the data structure used in the condition does.
Common Mistakes and How to Avoid Them
A frequent error is trying to modify the dictionary being built while iterating over the source. Since the comprehension constructs a new dictionary, this is not an issue. However, you cannot refer to the dictionary being built inside the condition or value expression because the new name is not bound until the comprehension completes.
Another mistake is forgetting that the if clause filters items before the value expression is evaluated. If the value expression relies on an attribute, method, or key that is not present on filtered-out items, the condition must exclude those items first. For example, if an item can be None, check for None before indexing it in the value expression.
items = [{'name': 'a', 'val': 1}, None, {'name': 'b', 'val': 2}]
# This fails: None is not subscriptable
# result = {x['name']: x['val'] for x in items if x['val'] > 0}The corrected version checks that x is not None first:
result = {x['name']: x['val'] for x in items if x is not None and x['val'] > 0}Because and short-circuits, the second condition is only evaluated when x is not None.
Using Conditions with Dictionary Views and Nested Comprehensions
Conditions work with any iterable, including dictionary views. Iterating over .items() lets you filter on both keys and values. This is common when cleaning up a dictionary by removing entries that fail a predicate.
original = {'a': 1, 'b': -2, 'c': 3}
positive = {k: v for k, v in original.items() if v > 0}You can also nest comprehensions, though readability suffers. A nested dictionary comprehension with a condition is useful when building nested structures from grouped data, but consider whether a helper function would be clearer.
groups = [('fruit', 'apple'), ('fruit', 'banana'), ('veg', 'carrot')]
grouped = {cat: {name for _, name in groups if _ == cat} for cat, _ in groups}This produces {'fruit': {'apple', 'banana'}, 'veg': {'carrot'}}. The inner comprehension filters items by the current category. The outer comprehension repeats category keys for each tuple, and duplicate keys collapse in the resulting dictionary. This approach is concise, but it re-scans groups for every tuple, making it O(n^2). For larger data, a loop with defaultdict(set) is more efficient and easier to maintain.
When a Dictionary Comprehension Is Not the Right Choice
The comprehension is concise when the key and value expressions are straightforward. If you need to perform side effects, such as logging or updating an external counter, a regular for loop is clearer because comprehensions are meant for pure transformations. Also, if the condition depends on the state of the dictionary being built (for example, checking whether a key already exists), you cannot reference the dictionary inside the comprehension. In such cases, build the dictionary incrementally with a loop.
# Cannot check membership in the result dict inside a comprehension
result = {}
for item in data:
if item.key not in result:
result[item.key] = item.valueThe comprehension syntax is designed for filtering and mapping, not for stateful accumulation. Recognizing this boundary helps you choose the right tool without forcing a comprehension into every situation.
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.