Just like List Comprehensions, Python has a feature called “Dictionary Comprehension” for efficiently generating and processing dictionaries (dict). Compared to creating a dictionary using a standard for loop, this method reduces the amount of code and improves readability. It can also offer performance benefits.
This article explains the basic syntax of dictionary comprehensions and four practical usage patterns.
Basic Syntax of Dictionary Comprehension
Dictionary comprehension is written by placing an expression that generates key-value pairs and a for loop inside {} (curly braces).
Syntax:
{key_expression: value_expression for variable in iterable}
Pattern 1: Generating a Dictionary from a List
The most basic usage is to take keys from an iterable (like a list) and assign a specific value (fixed or calculated) to create a dictionary. For example, let’s create a dictionary where all server statuses are initialized to “Active” from a list of server names.
# List of server names
server_list = ["web-01", "db-01", "cache-01"]
# Initialize with dictionary comprehension
# Key is the server name, Value is always "Active"
server_status = {server: "Active" for server in server_list}
print(f"Server Status: {server_status}")
Output:
Server Status: {'web-01': 'Active', 'db-01': 'Active', 'cache-01': 'Active'}
Pattern 2: Modifying an Existing Dictionary (Using .items())
This is useful when you want to batch-change the “values” of an existing dictionary to create a new one. In this case, use the .items() method of the original dictionary to extract keys and values. For example, let’s create a dictionary of tax-included prices (1.1x) from a dictionary of prices excluding tax.
# Dictionary of prices excluding tax
prices_excluding_tax = {
"Mouse": 2000,
"Keyboard": 5000,
"Monitor": 30000
}
# Create a new dictionary with values multiplied by 1.1
# Keep the key (item) as is, calculate the value (price)
prices_including_tax = {item: int(price * 1.1) for item, price in prices_excluding_tax.items()}
print(f"Tax Included: {prices_including_tax}")
Output:
Tax Included: {'Mouse': 2200, 'Keyboard': 5500, 'Monitor': 33000}
Pattern 3: Creating a Dictionary Conditionally (Using if)
By adding an if statement after the for loop, you can extract only the elements that meet a specific condition (Filtering). For example, let’s extract only the subjects with a passing score (60 or higher) from a dictionary of all subject scores.
# Scores for all subjects
all_scores = {
"Math": 85,
"Science": 92,
"History": 58,
"English": 45
}
# Extract only subjects with a score of 60 or higher
passing_scores = {subject: score for subject, score in all_scores.items() if score >= 60}
print(f"Passing Subjects: {passing_scores}")
Output:
Passing Subjects: {'Math': 85, 'Science': 92}
Pattern 4: Creating a Dictionary from Two Lists (Using zip)
If you have a “list of keys” and a “list of values” separately, you can combine them into a single dictionary using the zip() function and dictionary comprehension.
# List of IDs (Key)
user_ids = [101, 102, 103]
# List of Names (Value)
user_names = ["Tanaka", "Sato", "Suzuki"]
# Combine into a dictionary using zip
user_directory = {uid: name for uid, name in zip(user_ids, user_names)}
print(f"User Directory: {user_directory}")
Output:
User Directory: {101: 'Tanaka', 102: 'Sato', 103: 'Suzuki'}
Note: If you are simply combining them without modification, you can write dict(zip(user_ids, user_names)). However, dictionary comprehension is suitable if you want to modify the keys or values (e.g., converting IDs to strings) during creation.
Summary
- Dictionary comprehension is written in the format
{key: value for var in iterable}. - It is more concise than repeating
dict[key] = valuein aforloop. - Combining with
.items()allows for batch conversion of existing dictionary values. - Combining with
ifallows for filtering dictionary elements. - Combining with
zip()allows you to merge two lists into a dictionary.
