- Basic syntax — how dictionary comprehension works
- Filtering — using if to pick certain items
- if-else — deciding values based on conditions
- Nested comprehension — working with nested loops
- Swapping — flipping keys and values
- Common mistakes — and how to avoid them
What is Dictionary Comprehension?
Dictionary comprehension is a neat way to create dictionaries in Python. Instead of writing a loop with several lines of code, you can do it all in one line. It's like a shortcut that makes your code shorter and often easier to read.
Think of it this way: you have some data, you want to transform it into a dictionary, and you want to do it quickly. Dictionary comprehension does exactly that.
Here's the basic structure:
{key: value for item in iterable if condition}
Let's break that down:
- key — what you want as the key
- value — what you want as the value
- item — each element from your source
- iterable — where the data comes from (list, range, etc.)
- if condition — optional, filters which items to include
💡 Here's the thing: Dictionary comprehension is great for simple transformations. If your logic gets too complicated, a regular loop might be easier to understand.
Basic Syntax
Your First Dictionary Comprehension
Let's start with something simple. Say you have a list of numbers and you want a dictionary where each number is the key and its square is the value.
# Traditional way (using a loop)
numbers = [1, 2, 3, 4, 5]
squares = {}
for num in numbers:
squares[num] = num ** 2
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# With dictionary comprehension (much shorter!)
squares = {num: num ** 2 for num in numbers}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Using a range
squares = {x: x ** 2 for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# With strings
words = ["apple", "banana", "cherry"]
word_lengths = {word: len(word) for word in words}
print(word_lengths) # {'apple': 5, 'banana': 6, 'cherry': 6}
What's happening here:
- We go through each item in the list
- We create a key-value pair for each item
- The result is a brand new dictionary
- The original list stays unchanged
Quick Check: What does dictionary comprehension return? (Answer: A new dictionary)
Filtering with if
Only Keep What You Want
Sometimes you don't want everything. You only want certain items. The if clause lets you filter.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Only keep even numbers
even_squares = {num: num ** 2 for num in numbers if num % 2 == 0}
print(even_squares) # {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
# Only numbers greater than 5
big_numbers = {num: num ** 2 for num in numbers if num > 5}
print(big_numbers) # {6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
# With strings — words longer than 5 characters
words = ["apple", "banana", "cherry", "date", "elderberry"]
long_words = {word: len(word) for word in words if len(word) > 5}
print(long_words) # {'banana': 6, 'cherry': 6, 'elderberry': 10}
How it works:
- The
ifchecks each item - Only items that pass the test are included
- Items that don't pass are skipped
- You can combine this with transformation
Quick Check: What does the if clause do? (Answer: It filters items — only those that satisfy the condition are included)
if-else in Expression
Deciding Values Based on Conditions
Sometimes you want different values depending on the item. You can use if-else inside the expression part.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Label numbers as "even" or "odd"
labels = {num: "even" if num % 2 == 0 else "odd" for num in numbers}
print(labels) # {1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd', 6: 'even', 7: 'odd', 8: 'even', 9: 'odd', 10: 'even'}
# Mark numbers greater than 5 as "high", others as "low"
categories = {num: "high" if num > 5 else "low" for num in numbers}
print(categories) # {1: 'low', 2: 'low', 3: 'low', 4: 'low', 5: 'low', 6: 'high', 7: 'high', 8: 'high', 9: 'high', 10: 'high'}
# Square even numbers, leave odd numbers as they are
processed = {num: num ** 2 if num % 2 == 0 else num for num in numbers}
print(processed) # {1: 1, 2: 4, 3: 3, 4: 16, 5: 5, 6: 36, 7: 7, 8: 64, 9: 9, 10: 100}
Important difference:
- if at the end — filters items out completely
- if-else in expression — changes the value but keeps the item
Quick Check: What's the difference between if at the end and if-else in expression? (Answer: if at the end filters; if-else in expression transforms)
Nested Dictionary Comprehension
Working with Nested Loops
You can use nested loops in dictionary comprehension, just like you would with regular loops.
# Create a multiplication table
table = {i: {j: i * j for j in range(1, 4)} for i in range(1, 4)}
print(table)
# {1: {1: 1, 2: 2, 3: 3}, 2: {1: 2, 2: 4, 3: 6}, 3: {1: 3, 2: 6, 3: 9}}
# Flatten a matrix with indices
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = {(i, j): matrix[i][j] for i in range(3) for j in range(3)}
print(flattened)
# {(0, 0): 1, (0, 1): 2, (0, 2): 3, (1, 0): 4, (1, 1): 5, (1, 2): 6, (2, 0): 7, (2, 1): 8, (2, 2): 9}
# List of lists to dictionary with indices
data = [["apple", "banana"], ["cherry", "date"]]
result = {i: {j: item for j, item in enumerate(row)} for i, row in enumerate(data)}
print(result)
# {0: {0: 'apple', 1: 'banana'}, 1: {0: 'cherry', 1: 'date'}}
Tips:
- Nested comprehension follows the same order as nested loops
- It can get hard to read with too many levels
- Sometimes a regular loop is easier to understand
Multiple Conditions
Combining Filters
You can use multiple if clauses or combine conditions with and and or.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Multiple if clauses (acts as AND)
result = {num: num ** 2 for num in numbers if num > 3 if num < 8}
print(result) # {4: 16, 5: 25, 6: 36, 7: 49}
# Using and
result = {num: num ** 2 for num in numbers if num > 3 and num < 8}
print(result) # {4: 16, 5: 25, 6: 36, 7: 49}
# Using or
result = {num: num ** 2 for num in numbers if num % 2 == 0 or num > 7}
print(result) # {2: 4, 4: 16, 6: 36, 8: 64, 9: 81, 10: 100}
Keep it simple:
- Multiple
ifclauses are less common - Using
andandoris usually clearer - Don't overcomplicate — readability matters
Swapping Keys and Values
Flipping Your Dictionary
One common use of dictionary comprehension is swapping keys and values. This is useful when you need to look up by the value instead of the key.
# Swap keys and values
original = {"apple": 5, "banana": 3, "cherry": 8}
swapped = {value: key for key, value in original.items()}
print(swapped) # {5: 'apple', 3: 'banana', 8: 'cherry'}
# Be careful with duplicate values (last one wins)
colors = {"red": "#FF0000", "green": "#00FF00", "blue": "#0000FF"}
color_names = {value: key for key, value in colors.items()}
print(color_names) # {'#FF0000': 'red', '#00FF00': 'green', '#0000FF': 'blue'}
# With a condition
scores = {"Alice": 85, "Bob": 92, "Charlie": 78}
reversed_scores = {score: name for name, score in scores.items() if score >= 80}
print(reversed_scores) # {85: 'Alice', 92: 'Bob'}
Things to watch out for:
- If two keys have the same value, one will be lost
- Values must be hashable to be used as keys
- This is a great way to create a reverse lookup
Quick Check: What happens if two keys have the same value when swapping? (Answer: The last one overwrites the first)
Common Mistakes
Things to Watch Out For
Confusing Filter and Transformation
# WRONG — trying to use if-else as a filter
numbers = [1, 2, 3, 4, 5]
# result = {num: num ** 2 if num % 2 == 0 for num in numbers} # SyntaxError
# CORRECT — if-else in expression, if at end for filtering
result = {num: num ** 2 for num in numbers if num % 2 == 0} # Filter
result = {num: "even" if num % 2 == 0 else "odd" for num in numbers} # Transform
Using the Wrong Variable
# WRONG — using x when you meant num
numbers = [1, 2, 3, 4, 5]
# squares = {num: x ** 2 for x in numbers} # num is not defined
# CORRECT — use the same variable name
squares = {num: num ** 2 for num in numbers}
Overcomplicating Things
# TOO COMPLEX — hard to read
result = {x: x ** 2 if x % 2 == 0 else x ** 3 if x % 3 == 0 else x for x in range(1, 20)}
# BETTER — use a regular loop for complex logic
result = {}
for x in range(1, 20):
if x % 2 == 0:
result[x] = x ** 2
elif x % 3 == 0:
result[x] = x ** 3
else:
result[x] = x
Quick Check: When should you avoid dictionary comprehension? (Answer: When the logic gets too complex to read easily)
Try It Yourself
Play with dictionary comprehension in the editor below. Change the code and see what happens.
DICTIONARY COMPREHENSION PRACTICE
========================================
Numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Words: ['apple', 'banana', 'cherry', 'date', 'elderberry']
1. BASIC COMPREHENSION
Squares: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
2. WITH FILTERING
Even squares: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
3. IF-ELSE IN EXPRESSION
Labels: {1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd', 6: 'even', 7: 'odd', 8: 'even', 9: 'odd', 10: 'even'}
4. WITH STRINGS
Word lengths: {'apple': 5, 'banana': 6, 'cherry': 6, 'date': 4, 'elderberry': 10}
5. SWAPPING KEYS AND VALUES
Original: {'apple': 5, 'banana': 3, 'cherry': 8}
Swapped: {5: 'apple', 3: 'banana', 8: 'cherry'}
Dictionary comprehension practice complete!
You've Got It!
You now understand dictionary comprehension — basic syntax, filtering, if-else, nested comprehension, and swapping keys and values. These are handy skills for working with dictionaries.
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is dictionary comprehension?
{key: value for item in iterable} and Python builds the dictionary for you.
What's the difference between if at the end and if-else in expression?
Can I use nested comprehension?
Is dictionary comprehension faster than a loop?
What happens if I use duplicate keys in comprehension?
Can I use dictionary comprehension with nested loops?
Where to Go From Here
Now that you've got dictionary comprehension down, check out these related topics:
Dictionary Assignments
Practice what you've learned with assignments.
Learn More →List Comprehension
Create lists concisely with comprehension.
Learn More →Set Comprehension
Create sets using comprehension syntax.
Learn More →