PYTHON
Python Dictionary Comprehension: Syntax, Usage, and Examples
Dictionary comprehension lets you create a dictionary in one readable line by generating key-value pairs from an iterable. It’s a clean way to transform data, filter items, and build lookup tables without writing a full loop.
If you’ve used a list comprehension, dictionary comprehension follows the same idea, but you generate key-value pairs instead of a list.
Learn Python on Mimo
How to Use Dictionary Comprehension in Python
A dictionary comprehension uses curly braces {} and a key: value expression inside them.
Basic syntax
Python
{key_expression: value_expressionfor itemin iterable}
- key_expression: what each key should be
- value_expression: what each value should be
- item: a variable that represents each element in the iterable
- iterable: something you can loop over, like a list, tuple, string, range, or dictionary
Here’s a simple example that maps numbers to their squares:
Python
squares = {n: n * nfor ninrange(1,6)}
print(squares)# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Under the hood, this does the same job as a for loop, just in a more compact form.
Creating a dictionary from a list of keys
If you already have keys and want to compute their values, dictionary comprehension feels natural:
Python
names = ["Amir","Lena","Noa"]
lengths = {name:len(name)for namein names}
print(lengths)# {'Amir': 4, 'Lena': 4, 'Noa': 3}
This creates a new dictionary in one step, without needing to call append or build a temporary list first.
Adding a condition
You can filter items using an if clause at the end:
Python
{key_expression: value_expressionfor itemin iterableif condition}
Example: keep only even numbers:
Python
even_squares = {n: n * nfor ninrange(1,11)if n %2 ==0}
print(even_squares)# {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
That if clause is one of the most useful conditional statements you can combine with comprehensions when you want to filter data quickly.
Using an if/else expression
If you want the value to change depending on a condition, you can use a conditional expression:
Python
status_by_score = {
score:"pass"if score >=50else"retry"
for scorein [30,55,80]
}
print(status_by_score)# {30: 'retry', 55: 'pass', 80: 'pass'}
Working with two values at once
A common pattern is looping over pairs, for example tuples or results of enumerate().
Python
items = [("apple",3), ("banana",5), ("pear",2)]
inventory = {name: countfor name, countin items}
print(inventory)# {'apple': 3, 'banana': 5, 'pear': 2}
If you have two separate lists and want each key to match its corresponding value, the zip() function is a common fit for this pattern.
Dictionary comprehension vs dict() + loop
You can always build a dictionary using a loop:
Python
names = ["Amir","Lena","Noa"]
lengths = {}
for namein names:
lengths[name] =len(name)
Dictionary comprehension does the same thing with less code:
Python
lengths = {name:len(name)for namein names}
If you prefer a more explicit style, you can also build the same result with the dict() constructor, which can feel familiar if you’re learning the fundamentals of Python 3.
When to Use Dictionary Comprehension
Dictionary comprehension shines when you want to build a dictionary fast and keep the logic readable.
1) Creating lookup tables
Lookup tables help you go from one value to another quickly, like mapping codes to labels.
Example: convert short codes into full names:
Python
codes = ["bg","hr","at"]
country_names = {code: code.upper()for codein codes}
print(country_names)# {'bg': 'BG', 'hr': 'HR', 'at': 'AT'}
In real apps, you might map IDs to usernames, or language codes to translations.
2) Transforming values while keeping the same keys
Sometimes your keys are good, but you need different values.
Example: convert prices from strings into floats:
Python
prices = {"coffee":"2.50","tea":"1.90","cake":"3.20"}
prices_float = {item:float(price)for item, pricein prices.items()}
print(prices_float)# {'coffee': 2.5, 'tea': 1.9, 'cake': 3.2}
3) Filtering a dictionary
Filtering with dictionary comprehension feels like using a sieve.
Example: keep only items above a certain rating:
Python
ratings = {"Ali":4.7,"Mina":3.9,"Jordan":4.2}
top_rated = {name: ratingfor name, ratingin ratings.items()if rating >=4.0}
print(top_rated)# {'Ali': 4.7, 'Jordan': 4.2}
4) Normalizing messy input
User input can have inconsistent casing and whitespace. Dictionary comprehension helps you clean it quickly.
Example: clean keys while keeping values:
Python
raw = {" Email ":"nora@example.com","Name":"Nora"," CITY":"Boston"}
cleaned = {key.strip().lower(): valuefor key, valuein raw.items()}
print(cleaned)# {'email': 'nora@example.com', 'name': 'Nora', 'city': 'Boston'}
5) Creating a dictionary from a list of objects
If you have a list of dictionaries (or objects), you can turn it into a dictionary keyed by something meaningful.
Example: store users by their ID:
Python
users = [
{"id":101,"name":"Ravi"},
{"id":102,"name":"Elena"},
{"id":103,"name":"Sofia"}
]
users_by_id = {user["id"]: userfor userin users}
print(users_by_id[102])# {'id': 102, 'name': 'Elena'}
Examples of Dictionary Comprehension
Let’s build some common patterns you’ll run into when writing Python.
Example 1: Count occurrences of words
You can create a dictionary that maps each word to its count. A set helps avoid counting the same word key multiple times.
Python
sentence ="code code learn repeat learn"
words = sentence.split()
counts = {word: words.count(word)for wordinset(words)}
print(counts)# {'repeat': 1, 'learn': 2, 'code': 2}
This works fine for small text. For larger datasets, you’d normally use collections.Counter, but the example shows the idea clearly.
Example 2: Flip keys and values
Sometimes you want the reverse mapping. This works only when the values are unique.
Python
colors = {"primary":"purple","secondary":"gray"}
flipped = {value: keyfor key, valuein colors.items()}
print(flipped)# {'purple': 'primary', 'gray': 'secondary'}
If two keys share the same value, the last one will overwrite the earlier one.
Example 3: Convert a list into an indexed dictionary
enumerate() gives you index-value pairs. Dictionary comprehension turns them into a dictionary instantly.
Python
tasks = ["Write tests","Fix bug","Deploy"]
task_by_id = {i: taskfor i, taskinenumerate(tasks, start=1)}
print(task_by_id)# {1: 'Write tests', 2: 'Fix bug', 3: 'Deploy'}
This is handy when you want quick lookup by an ID-like number.
Example 4: Create a dictionary of formatted strings
A common real-world use is building display-ready values.
Python
users = ["Aya","Chris","Zara"]
greetings = {name:f"Hi {name}!"for namein users}
print(greetings["Zara"])# Hi Zara!
You can store UI labels, friendly messages, or tooltips this way.
Example 5: Parse key-value pairs from a list of strings
Imagine configuration data coming in as "key=value" lines.
Python
lines = ["mode=dark","lang=en","limit=10"]
config = {line.split("=")[0]: line.split("=")[1]for linein lines}
print(config)# {'mode': 'dark', 'lang': 'en', 'limit': '10'}
If you want safer parsing, you can split only once:
Python
config = {k: vfor k, vin (line.split("=",1)for linein lines)}
In practice, you’ll see dictionary comprehension a lot in data science workflows and quick experiments for machine learning, especially when you need a fast lookup before loading data into Pandas.
Learn More About Dictionary Comprehension
Dictionary comprehension is easy to read when it’s short. A few extra tips can keep you out of trouble.
Dictionary comprehension vs dict() and map()
People sometimes build dictionaries using dict() with transformations, but comprehension is usually clearer.
Python
nums = [1,2,3]
as_dict =dict((n, n * n)for nin nums)
The same result is easier to read like this:
Python
as_dict = {n: n * nfor nin nums}
Overwriting keys
Dictionaries can’t have duplicate keys. If your comprehension generates the same key more than once, the last value wins.
Python
values = ["A","a","A "]
result = {v.strip().lower(): vfor vin values}
print(result)# {'a': 'A '}
That’s not a bug, it’s how dictionaries work. If you need to keep multiple values per key, you may want lists as values instead.
If you’re updating an existing dictionary, pay attention to whether you’re replacing a dictionary value for a key that already exists.
Using functions inside comprehension
Comprehensions can call functions, which is great, but don’t cram too much logic into one line.
Readable example:
Python
names = [" Mina "," Ravi "," Elena "]
clean = {name.strip().lower():len(name.strip())for namein names}
Hard-to-read example:
Python
clean = {n.strip().lower():len(n.strip())for nin namesif nandlen(n.strip()) >2}
If your comprehension starts looking like a tiny essay, break it into steps.
If you need a tiny transformation inline, a lambda can work, but it often reads better to use a named function once the logic gets longer.
Nested loops inside a dictionary comprehension
You can combine loops, but clarity matters.
Example: create a dictionary of (row, col) positions:
Python
grid = {(r, c): r * cfor rinrange(1,4)for cinrange(1,4)}
print(grid[(2,3)])# 6
This is useful for grids, coordinate maps, or building lookup structures.
Filtering keys vs filtering values
You can filter based on keys, values, or both.
Filter by key:
Python
data = {"name":"Nora","password":"1234","city":"Boston"}
safe = {k: vfor k, vin data.items()if k !="password"}
Filter by value:
Python
scores = {"Ava":90,"Sam":45,"Kai":70}
passed = {name: scorefor name, scorein scores.items()if score >=60}
Memory and performance notes
Dictionary comprehension builds the full dictionary immediately. That’s what you want most of the time.
If you’re dealing with massive datasets, you might build things gradually or stream data, but for everyday scripts and apps, comprehension is a great balance of speed and readability.
Common beginner mistake: missing .items()
When looping over a dictionary directly, you only get keys:
Python
data = {"a":1,"b":2}
for itemin data:
print(item)# prints keys only
Dictionary comprehension usually needs both keys and values, so you use .items():
Python
swapped = {v: kfor k, vin data.items()}
print(swapped)# {1: 'a', 2: 'b'}
If you share snippets on Github, adding one short comment above a comprehension can help other readers see the intent right away.
Dictionary comprehensions are sometimes referred to as dict comprehensions; both names describe the same feature.
Summary
Dictionary comprehension helps you build dictionaries quickly by generating key-value pairs in one line. Use it to create lookup tables, transform values, filter items, and reshape data into a format that’s easier to work with.
Keep comprehensions short enough to read at a glance, and switch to a regular loop when your logic starts piling up.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot