Python
Dictionary Comprehension
Programming
Data Structures
Code Optimization

Python Dictionary Comprehension

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Dictionary comprehension is a concise syntax for creating dictionaries in Python, analogous to list comprehension for lists. Instead of writing multi-line loops to build a dictionary, you express the key-value mapping in a single expression. It is faster than equivalent for loops, more readable for simple transformations, and widely used for filtering, transforming, and inverting dictionaries.

Basic Syntax

python
1# {key_expression: value_expression for item in iterable}
2
3squares = {x: x**2 for x in range(6)}
4print(squares)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

This is equivalent to:

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

From Two Lists (zip)

Create a dictionary by pairing elements from two lists:

python
1keys = ['name', 'age', 'city']
2values = ['Alice', 30, 'New York']
3
4person = {k: v for k, v in zip(keys, values)}
5print(person)  # {'name': 'Alice', 'age': 30, 'city': 'New York'}
6
7# Equivalent shorthand using dict()
8person = dict(zip(keys, values))

Filtering with Conditions

Add an if clause to include only items that meet a condition:

python
1scores = {'Alice': 85, 'Bob': 42, 'Carol': 91, 'Dave': 67}
2
3# Keep only passing scores (>= 60)
4passing = {name: score for name, score in scores.items() if score >= 60}
5print(passing)  # {'Alice': 85, 'Carol': 91, 'Dave': 67}
6
7# Filter by key
8vowel_scores = {name: score for name, score in scores.items()
9                if name[0] in 'AEIOU'}
10print(vowel_scores)  # {'Alice': 85}

Transforming Keys or Values

python
1prices = {'apple': 1.20, 'banana': 0.50, 'cherry': 2.00}
2
3# Transform values (apply discount)
4discounted = {item: round(price * 0.9, 2) for item, price in prices.items()}
5print(discounted)  # {'apple': 1.08, 'banana': 0.45, 'cherry': 1.8}
6
7# Transform keys (uppercase)
8upper = {item.upper(): price for item, price in prices.items()}
9print(upper)  # {'APPLE': 1.20, 'BANANA': 0.50, 'CHERRY': 2.00}
10
11# Transform both
12formatted = {item.title(): f"${price:.2f}" for item, price in prices.items()}
13print(formatted)  # {'Apple': '$1.20', 'Banana': '$0.50', 'Cherry': '$2.00'}

Inverting a Dictionary

Swap keys and values:

python
1original = {'a': 1, 'b': 2, 'c': 3}
2
3inverted = {v: k for k, v in original.items()}
4print(inverted)  # {1: 'a', 2: 'b', 3: 'c'}

If multiple keys map to the same value, the last one wins:

python
1grades = {'Alice': 'A', 'Bob': 'B', 'Carol': 'A'}
2inverted = {v: k for k, v in grades.items()}
3print(inverted)  # {'A': 'Carol', 'B': 'Bob'} — Alice is lost!
4
5# To preserve all keys, map to lists
6from collections import defaultdict
7inv_multi = defaultdict(list)
8for k, v in grades.items():
9    inv_multi[v].append(k)
10print(dict(inv_multi))  # {'A': ['Alice', 'Carol'], 'B': ['Bob']}

Nested Dictionary Comprehension

Create dictionaries of dictionaries:

python
1# Multiplication table
2table = {i: {j: i * j for j in range(1, 4)} for i in range(1, 4)}
3print(table)
4# {1: {1: 1, 2: 2, 3: 3},
5#  2: {1: 2, 2: 4, 3: 6},
6#  3: {1: 3, 2: 6, 3: 9}}
7
8# Flatten a nested dict
9flat = {f"{outer}_{inner}": val
10        for outer, inner_dict in table.items()
11        for inner, val in inner_dict.items()}
12print(flat)  # {'1_1': 1, '1_2': 2, '1_3': 3, '2_1': 2, ...}

Conditional Expressions (if-else)

Use a ternary expression in the value (not a filter):

python
1numbers = range(-3, 4)
2
3# Classify as positive or negative
4classified = {n: 'positive' if n > 0 else 'negative' if n < 0 else 'zero'
5              for n in numbers}
6print(classified)
7# {-3: 'negative', -2: 'negative', -1: 'negative', 0: 'zero',
8#  1: 'positive', 2: 'positive', 3: 'positive'}

Note the difference: if after the for filters items out, while if-else in the value expression transforms every item.

From enumerate

python
1fruits = ['apple', 'banana', 'cherry']
2
3indexed = {i: fruit for i, fruit in enumerate(fruits)}
4print(indexed)  # {0: 'apple', 1: 'banana', 2: 'cherry'}
5
6# Reverse: fruit → index
7lookup = {fruit: i for i, fruit in enumerate(fruits)}
8print(lookup)  # {'apple': 0, 'banana': 1, 'cherry': 2}

Performance: Comprehension vs Loop

Dictionary comprehension is generally 10-30% faster than equivalent for loops because the iteration happens in C-optimized code:

python
1import timeit
2
3# Comprehension
4timeit.timeit('{x: x**2 for x in range(1000)}', number=10000)
5# ~1.2 seconds
6
7# Loop
8timeit.timeit('''
9d = {}
10for x in range(1000):
11    d[x] = x**2
12''', number=10000)
13# ~1.5 seconds

Common Pitfalls

  • Duplicate keys silently overwrite: If the key expression produces duplicate keys, later values silently replace earlier ones. There is no error or warning. Use a list of tuples or defaultdict(list) if you need to preserve all values.
  • Readability vs cleverness: Comprehensions with multiple conditions, nested loops, and complex expressions become harder to read than explicit loops. If the comprehension exceeds one line, consider a regular loop.
  • Side effects: Dictionary comprehensions should not have side effects (like modifying external variables). Use a loop instead if you need side effects.
  • Memory with large datasets: A comprehension creates the entire dictionary in memory at once. For very large datasets, consider using a generator with dict() or processing items lazily.
  • Key must be hashable: Dictionary keys must be immutable and hashable (strings, numbers, tuples of hashable items). Using lists or dicts as keys raises TypeError.

Summary

  • Basic syntax: {key: value for item in iterable}
  • Add if condition after the for clause to filter items
  • Use zip(keys, values) to create dicts from two parallel lists
  • Use {v: k for k, v in d.items()} to invert a dictionary
  • Comprehensions are faster than equivalent for loops for building dictionaries
  • Keep comprehensions simple — use loops for complex logic with multiple conditions

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.