Python
Programming
Data Structures
Dictionary Comprehension
Code Optimization

Create a dictionary with comprehension

Master System Design with Codemia

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

Introduction

Dictionary comprehensions let you build a dictionary in one expression instead of writing an explicit loop. They are compact, readable when used well, and especially useful when you are transforming or filtering data.

The Basic Syntax

The pattern is:

python
{key_expression: value_expression for item in iterable}

A simple example maps numbers to their squares:

python
squares = {n: n * n for n in range(1, 6)}
print(squares)

Output:

text
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

This does the same work as a loop, but keeps the dictionary-building rule in one place.

Building a Dictionary from Two Iterables

Comprehensions are often used when keys and values come from existing collections.

python
1keys = ["name", "age", "city"]
2values = ["Alice", 30, "Toronto"]
3
4person = {k: v for k, v in zip(keys, values)}
5print(person)

This is equivalent to dict(zip(keys, values)), but the comprehension form is useful when the value needs transformation too.

Filtering While Building

You can add a condition at the end.

python
scores = {"Alice": 85, "Bob": 42, "Cara": 91, "Dan": 58}
passing = {name: score for name, score in scores.items() if score >= 60}
print(passing)

This is one of the best use cases for dictionary comprehensions because the selection rule and the output mapping stay together.

Transforming an Existing Dictionary

You can also keep the same keys and change the values.

python
prices = {"apple": 1.5, "banana": 0.75, "orange": 2.0}
discounted = {item: round(price * 0.9, 2) for item, price in prices.items()}
print(discounted)

This is cleaner than mutating the original dictionary when you want a new result rather than an in-place update.

Swapping Keys and Values

Another common pattern is inversion:

python
codes = {"red": "#ff0000", "green": "#00ff00", "blue": "#0000ff"}
inverted = {value: key for key, value in codes.items()}
print(inverted)

This works only when the values are unique. If multiple original keys share the same value, later entries overwrite earlier ones.

Nested and Conditional Expressions

You can include conditional expressions inside the value expression itself:

python
numbers = range(1, 6)
labels = {n: ("even" if n % 2 == 0 else "odd") for n in numbers}
print(labels)

This is still readable because the rule is small. Once the logic becomes much more complex, a normal loop is usually better.

Equivalent Loop Form

It helps to see what the comprehension expands to:

python
result = {}
for n in range(1, 6):
    result[n] = n * n

The comprehension is not magic. It is just a shorter way to express this dictionary-building pattern.

When Not to Use One

Comprehensions are best when the mapping rule is short and obvious. If you need multiple branches, logging, exception handling, or several nested conditions, a plain loop is easier to debug and maintain.

Readable code matters more than saving a few lines.

Common Pitfalls

Forgetting that duplicate keys overwrite previous values can produce surprising results.

Packing too much logic into one comprehension makes it harder to read than the loop it replaced.

Using a comprehension when dict(zip(...)) is simpler can make code look more clever than necessary.

Assuming the comprehension preserves every source item even when multiple items generate the same key is incorrect.

Summary

  • Dictionary comprehensions use the form key: value for ....
  • They are great for concise transformation and filtering.
  • They work well for building dictionaries from iterables or existing mappings.
  • Duplicate keys do not accumulate; later values replace earlier ones.
  • If the rule becomes hard to read, switch back to a normal loop.

Course illustration
Course illustration

All Rights Reserved.