Dictionary Comprehensions Explained
A dictionary comprehension is a short way to create a dictionary in Python.
It lets you build keys and values in one line instead of writing a full loop. This is useful when you want to transform existing data into a new dictionary.
If you already know what a Python dictionary is, this is the next step toward writing shorter and cleaner code. If not, read Python dictionaries explained first.
Quick example
numbers = [1, 2, 3, 4]
squares = {n: n * n for n in numbers}
print(squares)
# {1: 1, 2: 4, 3: 9, 4: 16}
A dictionary comprehension builds a dictionary in one line using key: value for item in iterable.
What a dictionary comprehension is
A dictionary comprehension is:
- A short way to create a dictionary
- A combination of a loop and dictionary creation in one expression
- A way to produce a new dictionary
- Useful when keys and values can be built from existing data
You can think of it like this:
- Python loops through some data
- For each item, it creates a key
- It also creates a value
- It stores them in a new dictionary
This makes dictionary comprehensions helpful for tasks like:
- Building lookup tables
- Changing the shape of data
- Filtering items while creating a dictionary
Basic syntax
The general form is:
{key_expression: value_expression for item in iterable}
Each part has a job:
key_expressioncreates the dictionary keyvalue_expressioncreates the dictionary valuefor item in iterableloops through the data
You can also add a condition at the end:
{key_expression: value_expression for item in iterable if condition}
That if filters items before they are added to the dictionary.
Example of the syntax
numbers = [1, 2, 3]
result = {n: n + 10 for n in numbers}
print(result)
Output:
{1: 11, 2: 12, 3: 13}
Here:
nis the current item from the listnbecomes the keyn + 10becomes the value
Simple example with a list
A common use is creating a dictionary from a list of values.
numbers = [1, 2, 3, 4]
squares = {n: n * n for n in numbers}
print(squares)
Output:
{1: 1, 2: 4, 3: 9, 4: 16}
What this does:
- Loops through each number in
numbers - Uses the number itself as the key
- Uses the square of the number as the value
You are not limited to numbers. You can also use strings.
words = ["cat", "dog", "elephant"]
lengths = {word: len(word) for word in words}
print(lengths)
Output:
{'cat': 3, 'dog': 3, 'elephant': 8}
This creates a dictionary where:
- Each word is a key
- Each value is the length of that word
If you want to compare this idea with another comprehension type, see list comprehensions in Python explained.
Using conditions in a dictionary comprehension
You can add if to keep only some items.
For example, this keeps only even numbers:
numbers = [1, 2, 3, 4, 5, 6]
even_squares = {n: n * n for n in numbers if n % 2 == 0}
print(even_squares)
Output:
{2: 4, 4: 16, 6: 36}
How it works:
- Python loops through all numbers
- It checks
n % 2 == 0 - Only even numbers are added to the dictionary
This is useful because filtering happens during dictionary creation. You do not need extra lines to build the dictionary step by step.
You can also filter an existing dictionary. To do that, you will often use .items(). See Python dictionary items() method if that method is new to you.
Example:
prices = {"apple": 2, "banana": 1, "cherry": 3}
expensive = {key: value for key, value in prices.items() if value >= 2}
print(expensive)
Output:
{'apple': 2, 'cherry': 3}
Dictionary comprehension vs normal loop
Dictionary comprehensions are useful, but they are not always the best choice.
Use a dictionary comprehension when:
- The transformation is short
- The logic is simple
- The result is easy to read in one line
Use a normal loop when:
- The logic is more complex
- You need multiple steps
- The one-line version is hard to understand
Same result with a normal loop
numbers = [1, 2, 3, 4]
squares = {}
for n in numbers:
squares[n] = n * n
print(squares)
Output:
{1: 1, 2: 4, 3: 9, 4: 16}
Same result with a dictionary comprehension
numbers = [1, 2, 3, 4]
squares = {n: n * n for n in numbers}
print(squares)
Both versions are correct.
The comprehension is shorter. The loop may feel clearer when you are still learning.
A good rule for beginners is:
- Prefer the clearest version
- Use a comprehension when it still feels easy to read
Common beginner mistakes
Here are some common problems beginners run into.
Forgetting the colon between key and value
This is wrong:
numbers = [1, 2, 3]
# result = {n n * n for n in numbers}
This is correct:
numbers = [1, 2, 3]
result = {n: n * n for n in numbers}
print(result)
The colon : is required because dictionaries store key: value pairs.
Using square brackets instead of curly braces
Square brackets create a list comprehension, not a dictionary comprehension.
Wrong shape:
numbers = [1, 2, 3]
result = [n * n for n in numbers]
print(result)
Output:
[1, 4, 9]
That is a list, not a dictionary.
Dictionary comprehensions must use curly braces:
numbers = [1, 2, 3]
result = {n: n * n for n in numbers}
print(result)
Trying to do too much in one comprehension
Short code is not always better.
If your comprehension becomes hard to read, rewrite it as a normal loop. This is especially important for beginners.
Creating duplicate keys without noticing
Dictionary keys must be unique.
If two items create the same key, the later value replaces the earlier one.
words = ["cat", "dog", "cat"]
result = {word: len(word) for word in words}
print(result)
Output:
{'cat': 3, 'dog': 3}
There is only one "cat" key in the final dictionary.
When to use dictionary comprehensions
Dictionary comprehensions are a good choice when you want to:
- Build lookup tables from lists
- Convert one dictionary into another shape
- Filter dictionary items
- Create dictionaries from strings, ranges, or zipped data
From a string
text = "abc"
result = {char: char.upper() for char in text}
print(result)
Output:
{'a': 'A', 'b': 'B', 'c': 'C'}
From a range
result = {n: n * 10 for n in range(5)}
print(result)
Output:
{0: 0, 1: 10, 2: 20, 3: 30, 4: 40}
From zipped data
keys = ["name", "age", "city"]
values = ["Ana", 25, "Paris"]
result = {k: v for k, v in zip(keys, values)}
print(result)
Output:
{'name': 'Ana', 'age': 25, 'city': 'Paris'}
Common causes of confusion
Beginners often struggle with dictionary comprehensions because of these issues:
- Confusing list comprehensions with dictionary comprehensions
- Not understanding that dictionaries need
key: valuepairs - Using complex logic that is better written as a normal loop
- Accidentally overwriting values because keys repeat
If something looks wrong, these quick checks can help:
print(result)
print(type(result))
print(result.keys())
print(result.values())
for k, v in result.items():
print(k, v)
These checks help you confirm:
- Whether the result is really a dictionary
- Which keys were created
- Which values were created
- Whether the keys and values match what you expected
If you need more practice working with dictionary contents, read how to loop through a dictionary in Python and how to check if a key exists in a dictionary in Python.
FAQ
What is the difference between a list comprehension and a dictionary comprehension?
A list comprehension creates a list. A dictionary comprehension creates a dictionary with key: value pairs.
Can I use if in a dictionary comprehension?
Yes. You can add an if condition at the end to filter which items are included.
What happens if two items create the same key?
The later value replaces the earlier one because dictionary keys must be unique.
Should beginners use dictionary comprehensions?
Yes, for simple cases. If the code becomes hard to read, use a normal loop instead.
See also
- List comprehensions in Python explained
- Python dictionaries explained
- Python dictionary items() method
- How to loop through a dictionary in Python
- How to check if a key exists in a dictionary in Python
Compare a dictionary comprehension with a normal loop, then practice by turning a small list or dictionary into a new dictionary. That is the fastest way to get comfortable with this syntax.