Dict Comprehension
A dictionary comprehension is a syntax that creates a dictionary in a single line. Similar in form to list comprehensions, it lets you concisely express key-value transformations and filtering.
Syntax
# Basic dictionary comprehension
{key_expr: value_expr for variable in iterable}
# Dictionary comprehension with a condition
{key_expr: value_expr for variable in iterable if condition}
# Generate from an existing dictionary
{key: transform(value) for key, value in dictionary.items()}
Syntax Patterns
| Pattern | Description |
|---|---|
| {k: v for k, v in items()} | Converts all entries of a dictionary into a new dictionary. Any expression can be used for keys and values. |
| {k: v for k, v in items() if condition} | Creates a dictionary containing only entries that satisfy the condition. |
| {v: k for k, v in dictionary.items()} | Creates a dictionary with keys and values swapped. |
| {x: x**2 for x in range(n)} | Computes keys and values from an iterable such as a sequence of numbers. |
| dict(zip(keys, values)) | Creates a dictionary by pairing two lists as keys and values. |
Sample Code
# Create a dictionary that stores the square of each number.
squares = {x: x**2 for x in range(1, 6)}
print(squares) # Outputs: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Create a dictionary of only even numbers with a condition.
even_squares = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(even_squares) # Outputs: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
# Transform the values of an existing dictionary (multiply prices by 1.1).
prices = {'apple': 100, 'banana': 80, 'cherry': 200}
taxed = {k: int(v * 1.1) for k, v in prices.items()}
print(taxed) # Outputs: {'apple': 110, 'banana': 88, 'cherry': 220}
# Swap keys and values.
original = {'a': 1, 'b': 2, 'c': 3}
flipped = {v: k for k, v in original.items()}
print(flipped) # Outputs: {1: 'a', 2: 'b', 3: 'c'}
# Combine two lists with zip() to create a dictionary.
names = ['Alice', 'Bob', 'Carol']
scores = [85, 92, 78]
result = {name: score for name, score in zip(names, scores)}
print(result) # Outputs: {'Alice': 85, 'Bob': 92, 'Carol': 78}
# Use a list of strings as keys and their lengths as values.
words = ['python', 'java', 'javascript']
word_lengths = {w: len(w) for w in words}
print(word_lengths) # Outputs: {'python': 6, 'java': 4, 'javascript': 10}
# Extract a dictionary containing only specific keys.
profile = {'name': 'Alice', 'age': 30, 'city': 'New York', 'job': 'Engineer'}
allowed_keys = {'name', 'city'}
filtered = {k: v for k, v in profile.items() if k in allowed_keys}
print(filtered) # Outputs: {'name': 'Alice', 'city': 'New York'}
Overview
Dictionary comprehensions are one of Python's powerful features, allowing you to create a dictionary in a single line by combining a loop with an optional condition. Compared to building a dictionary with a regular for loop, this syntax is concise, readable, and considered Pythonic.
Because any expression can be used for both keys and values, dictionary comprehensions are useful in many situations — transforming existing dictionaries, filtering entries, and creating reverse-lookup dictionaries. If duplicate keys may occur, the last one processed takes precedence. Keys must also be hashable objects (such as strings, numbers, or tuples); lists cannot be used as keys.
For copying and merging dictionaries, see 'dict.copy() / dict() / Merging Dictionaries'.
If you find any errors or copyright issues, please contact us.