Course contentsShow
← Python
Lesson 284 of 1,0605. Advanced Iteration and ComprehensionsFree lesson

Mapping and Filtering Keys in Dictionary Comprehensions

Learners will practice applying conditional logic to both keys and values simultaneously while building dictionaries from existing datasets.

Mapping and Filtering Keys in Dictionary Comprehensions

In this lesson, you will learn how to refine your dictionary construction by applying conditional logic to both keys and values at the exact moment of creation.

When creating dictionaries from existing data, you often need to perform two tasks simultaneously: transforming the data (mapping) and deciding which data to include (filtering). While you’ve seen how to filter values before, dictionary comprehensions allow you to use a conditional expression for the key as well.

Logic on Both Sides of the Colon

The syntax for a dictionary comprehension is {key_expression: value_expression for item in iterable if condition}. To apply logic to the key, you can use an inline ternary operator—the same val_if_true if condition else val_if_false structure you’ve used with lists.

Consider a scenario where you have a list of server IDs, but you want a dictionary that groups them. You might want to map certain IDs to a "Critical" category while keeping others as "Standard":

servers = [101, 102, 103, 104]

# Map the key based on the value, and filter out even-numbered servers
server_dict = {
    (f"Critical_{s}" if s < 103 else f"Standard_{s}"): s 
    for s in servers 
    if s % 2 != 0
}

# Output: {'Critical_101': 101, 'Standard_103': 103}

Why This Matters

In the example above, the dictionary comprehension handles three distinct operations:

  1. Filtering: The if s % 2 != 0 clause ensures we only process odd-numbered servers.
  2. Mapping the Key: The ternary operator f"Critical_{s}" if s < 103 else f"Standard_{s}" dynamically generates the key string based on the value.
  3. Mapping the Value: Assigning s to the key completes the dictionary pair.

By keeping this logic inside the comprehension, you avoid the "clutter" of a multi-line for loop, keeping your data transformation declarative and concise. As long as the logic remains readable, this is an idiomatic way to reshape data structures on the fly.

Key Takeaway: Use inline ternary operators to transform keys dynamically while simultaneously applying filter conditions to control exactly which entries appear in your final dictionary.