python
dictionary comprehension
if else
conditional expressions
programming tips

How can I use if/else in a dictionary comprehension?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Python dictionary comprehensions support conditional logic, but there are two different patterns and they solve different problems. One pattern chooses between two values with if/else, while the other pattern filters items out entirely with a trailing if.

Use if/else Inside the Value Expression

If every key should stay in the dictionary, but the value depends on a condition, put the conditional expression where the value is produced.

python
1scores = {"alice": 92, "bob": 58, "carol": 77}
2
3labels = {
4    name: ("pass" if score >= 60 else "fail")
5    for name, score in scores.items()
6}
7
8print(labels)

This creates:

python
{'alice': 'pass', 'bob': 'fail', 'carol': 'pass'}

The key idea is that if/else here is an expression. It chooses a value for each key rather than controlling whether the key exists at all.

Use Trailing if to Filter Entries

If the goal is to keep only some items and omit the rest, use a trailing if after the for clause.

python
evens = {n: n * n for n in range(10) if n % 2 == 0}
print(evens)

This keeps only matching entries. There is no else in this form because non-matching items are dropped, not assigned an alternate value.

Think of it this way:

  • Value-level if/else decides what value to store.
  • Trailing if decides whether the key-value pair exists at all.

Combine Both Forms When Needed

You can use both patterns in the same comprehension when you need filtering and conditional values.

python
1nums = [1, 2, 3, 4, 5, 6]
2
3result = {
4    n: ("even" if n % 2 == 0 else "odd")
5    for n in nums
6    if n >= 3
7}
8
9print(result)

This keeps only numbers greater than or equal to 3, while still deciding whether each remaining value should be "even" or "odd".

That split makes the syntax easier to reason about once you know what each if is doing.

Understand the Syntax That Fails

The most common syntax error is trying to place a full if/else after the for clause as if it were a filter with two branches.

Incorrect:

python
# SyntaxError
# {k: v for k, v in data if condition else other}

Why it fails:

  • The trailing part after for supports a filter, not a full conditional expression.
  • Python expects either if condition for filtering or a value expression before for.

When you need two possible values, move the if/else expression back to the value side of the comprehension.

Real Example: Normalizing API Data

This pattern is especially useful when normalizing lightweight data from an API or CSV feed.

python
1users = [
2    {"id": 1, "is_active": True},
3    {"id": 2, "is_active": False},
4    {"id": 3, "is_active": True},
5]
6
7status_by_id = {
8    user["id"]: ("active" if user["is_active"] else "inactive")
9    for user in users
10}
11
12print(status_by_id)

That is concise and readable because the mapping rule is simple and side-effect free.

When a Normal Loop Is Better

Dictionary comprehensions are best when the transformation is compact. If the logic includes several branches, validation, logging, or side effects, a normal loop is clearer.

python
1result = {}
2
3for name, score in scores.items():
4    if score < 0:
5        raise ValueError(f"Invalid score for {name}")
6
7    if score >= 90:
8        result[name] = "excellent"
9    elif score >= 60:
10        result[name] = "pass"
11    else:
12        result[name] = "fail"
13
14print(result)

That version is longer, but it is also easier to debug and explain.

Readability Rules That Scale

As a rule of thumb:

  • Use a comprehension when the rule fits in one or two simple expressions.
  • Use a normal loop when you need multiple conditions or explanatory steps.
  • Avoid nested conditional expressions unless the team already uses them consistently.

A good heuristic is whether another developer can understand the comprehension on one pass. If not, it is too dense.

Common Pitfalls

  • Trying to use else in the trailing filter position.
  • Using a comprehension when the logic really needs multiple branches.
  • Forgetting parentheses around a longer conditional value expression.
  • Mixing filtering and value selection without being clear about which is which.
  • Writing one-line comprehensions that are shorter but much harder to maintain.

Summary

  • Put if/else in the value expression when every key should remain in the dictionary.
  • Use trailing if only when you want to filter items out completely.
  • You can combine both patterns in one dictionary comprehension.
  • If the condition becomes complex, switch to a regular loop for clarity.
  • The best comprehension is one that stays readable while still being concise.

Course illustration
Course illustration

All Rights Reserved.