Last modified: Jan 27, 2026 By Alexander Williams
Python Dict Comprehension Guide & Examples
Python dict comprehension is a powerful feature. It lets you create dictionaries in one line. This method is concise and efficient. It is a key skill for Python developers.
This guide explains dict comprehension. It covers the basic syntax. It shows practical examples. It also compares it to other methods.
What is Dict Comprehension?
Dict comprehension is a compact way to build dictionaries. You create them from iterables like lists or tuples. The syntax is similar to list comprehension.
It uses curly braces {}. Inside, you define a key-value pair and a loop. You can also add conditions. This makes your code shorter and often faster.
Basic Syntax of Dict Comprehension
The basic structure is simple. It is {key_expression: value_expression for item in iterable}. The key and value are expressions. They can use the current item.
Here is a first example. It creates a dictionary of squares.
# Basic dict comprehension: number to its square
numbers = [1, 2, 3, 4, 5]
squares_dict = {num: num ** 2 for num in numbers}
print(squares_dict)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The code loops through the list. For each number, it makes a key-value pair. The key is the number. The value is the number squared.
Adding Conditional Logic
You can filter items with an if statement. This adds power to your comprehensions. You process only the items that meet a condition.
Let's create a dictionary of even squares.
# Dict comprehension with a condition
numbers = [1, 2, 3, 4, 5, 6]
even_squares = {num: num ** 2 for num in numbers if num % 2 == 0}
print(even_squares)
{2: 4, 4: 16, 6: 36}
Only even numbers are processed. The if num % 2 == 0 part does the filtering. This is very useful for data cleaning.
Using Multiple Iterables
You can loop over two lists together. Use the zip() function. This pairs items from each list.
This is great for combining data.
# Creating a dict from two lists
keys = ['name', 'age', 'city']
values = ['Alice', 30, 'New York']
person_dict = {k: v for k, v in zip(keys, values)}
print(person_dict)
{'name': 'Alice', 'age': 30, 'city': 'New York'}
The zip() function pairs 'name' with 'Alice', and so on. The comprehension builds the dictionary from these pairs. For more on combining data structures, see our guide on how to import lists into a Python dictionary.
Transforming Existing Dictionaries
Dict comprehension is perfect for transforming dictionaries. You can modify keys, values, or both. You start with one dictionary and create a new one.
Here we convert temperatures from Celsius to Fahrenheit.
# Transforming dictionary values
celsius_temps = {'Mon': 22, 'Tue': 19, 'Wed': 25}
fahrenheit_temps = {day: (temp * 9/5) + 32 for (day, temp) in celsius_temps.items()}
print(fahrenheit_temps)
{'Mon': 71.6, 'Tue': 66.2, 'Wed': 77.0}
We use the .items() method to get key-value pairs. The new value is the converted temperature. The key remains the same. To understand other essential dictionary methods, check out our comprehensive Python dictionary methods guide.
Dict Comprehension vs For Loop
Why use comprehension? The main reason is readability. A single line often replaces four or five lines of a for loop. It is also slightly faster in many cases.
Compare the two methods below. They do the same thing.
# Method 1: Using a for loop
numbers = [1, 2, 3]
squares_loop = {}
for num in numbers:
squares_loop[num] = num ** 2
# Method 2: Using dict comprehension
squares_comp = {num: num ** 2 for num in numbers}
print("Loop result:", squares_loop)
print("Comprehension result:", squares_comp)
Loop result: {1: 1, 2: 4, 3: 9}
Comprehension result: {1: 1, 2: 4, 3: 9}
The comprehension is cleaner. It declares the intent upfront. It avoids the extra step of initializing an empty dictionary.
Common Use Cases and Examples
Dict comprehension is versatile. Here are some practical examples.
Swapping Keys and Values: This flips a dictionary. Be careful if values are not unique.
# Swap keys and values
original = {'a': 1, 'b': 2, 'c': 3}
swapped = {value: key for key, value in original.items()}
print(swapped)
{1: 'a', 2: 'b', 3: 'c'}
Creating a Lookup Table: Make a dictionary from a list of objects.
# Create a lookup dictionary
users = [{'id': 101, 'name': 'John'}, {'id': 102, 'name': 'Jane'}]
user_lookup = {user['id']: user['name'] for user in users}
print(user_lookup)
{101: 'John', 102: 'Jane'}
This creates a fast way to find a name by ID. It's a common pattern in data processing.
Potential Pitfalls and Best Practices
Dict comprehension is great. But you must use it wisely.
Avoid Overly Complex Comprehensions: If your logic gets long, use a for loop. Readability is more important than brevity.
Remember Key Uniqueness: Dictionary keys must be unique. If your comprehension creates duplicate keys, the last value wins. This can cause data loss.
Use for Readability: The main goal is cleaner code. Don't force a comprehension if a loop is clearer.
Sometimes you may need to modify an existing dictionary in-place. For that, the update method is more appropriate. Learn more in our detailed guide on the Python dict update method.
Conclusion
Python dict comprehension is a valuable tool. It creates dictionaries concisely. It improves code readability and performance.
Start with the basic syntax. Practice with conditions and transformations. Use it to replace simple for loops.
Remember to keep it simple. Do not write complex one-liners that are hard to read. Use dict comprehension to write elegant and efficient Python code.