dictionary comprehension
python programming
dictionary creation
python tips
coding techniques

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 are a concise way to build dictionaries from iterables in Python. They are useful when you need a direct mapping transformation, filtering, or normalization step in one readable expression. Used carefully, they produce cleaner code than manual loops while preserving explicit intent.

Dictionary Comprehension Fundamentals

The core form builds key-value pairs in a single expression.

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

This pattern replaces a loop that repeatedly assigns dictionary entries.

Equivalent loop form:

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

Both are valid. Comprehension is shorter, while loop form can be clearer for complex logic.

Filtering During Dictionary Creation

You can add an if condition to include only items that match criteria.

python
even_squares = {x: x * x for x in range(1, 11) if x % 2 == 0}
print(even_squares)

This avoids creating intermediate filtered lists and keeps selection logic next to mapping logic.

For readability, avoid stacking too many conditions in one line. If filtering rules are complex, compute them in a helper function first.

Creating Dictionaries from Existing Collections

A common use case is converting one structure into a keyed lookup dictionary.

python
1users = [
2    {"id": 10, "name": "Ava"},
3    {"id": 11, "name": "Mina"},
4    {"id": 12, "name": "Ravi"},
5]
6
7user_by_id = {u["id"]: u for u in users}
8print(user_by_id[11])

This gives fast key-based access and is common in API and ETL pipelines.

Another frequent pattern is zipping two lists:

python
1keys = ["name", "team", "region"]
2values = ["Ava", "platform", "ca-central"]
3
4profile = {k: v for k, v in zip(keys, values)}
5print(profile)

Use this only when list lengths are expected to align.

Normalizing Keys and Values

Comprehensions are helpful when you need normalization while creating a dictionary.

python
1raw = {
2    " User ": " Alice ",
3    "TEAM": "Platform",
4    "Region": " CA "
5}
6
7normalized = {k.strip().lower(): v.strip() for k, v in raw.items()}
8print(normalized)

This combines cleanup and mapping in one pass.

When normalization rules are domain-sensitive, document them clearly. Different teams may expect different handling for case and whitespace.

Handling Duplicate Keys from Source Data

When source data can produce duplicate keys, later entries overwrite earlier ones. This behavior is sometimes useful and sometimes dangerous.

python
pairs = [("env", "dev"), ("env", "prod"), ("region", "us")]
config = {k: v for k, v in pairs}
print(config)

Result keeps the last env value. If overwrites are not acceptable, detect duplicates before building the dictionary.

python
1seen = set()
2for k, _ in pairs:
3    if k in seen:
4        raise ValueError(f"duplicate key found: {k}")
5    seen.add(k)

Nested and Conditional Transformations

Comprehensions can build nested structures, but readability should remain the priority.

python
matrix = [[1, 2], [3, 4], [5, 6]]
row_sums = {i: sum(row) for i, row in enumerate(matrix)}
print(row_sums)

If nested loops and conditions make the expression hard to scan, split into multiple statements. Concision is useful only when clarity stays high.

Performance and Maintainability

Dictionary comprehensions are generally efficient and often faster than repeatedly calling dict.update in a loop. The bigger advantage is maintainability: the code states transformation intent directly.

Still, do not force everything into one expression. For complicated error handling, validation, or side effects, regular loops remain easier to debug and review.

A practical guideline:

  • simple transform: comprehension
  • complex workflow with branching: loop plus helper functions

Common Pitfalls

  • Writing overly complex one-liners that hide logic and hurt readability.
  • Forgetting duplicate key overwrite behavior when source data has collisions.
  • Using index-based list lookups instead of zip, reducing clarity.
  • Embedding expensive function calls in comprehension without profiling.
  • Choosing comprehension even when loop form would be clearer for validation-heavy logic.

Summary

  • Dictionary comprehensions are a compact, expressive way to build mappings.
  • They work well for direct transformations, filtering, and normalization.
  • Be explicit about duplicate key behavior because later values overwrite earlier ones.
  • Prefer readability over brevity when logic becomes complex.
  • Use comprehensions as a tool for clear intent, not as a mandatory style rule.

Course illustration
Course illustration

All Rights Reserved.