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.


How to Use Dictionary Comprehension in Python

A dictionary comprehension uses curly braces {} and a key: value expression inside them.

Basic syntax

{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:

squares = {n: n * nfor ninrange(1,6)}
print(squares)# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Creating a dictionary from a list of keys

If you already have keys and want to compute their values, dictionary comprehension feels natural:

names = ["Amir","Lena","Noa"]
lengths = {name:len(name)for namein names}

print(lengths)# {'Amir': 4, 'Lena': 4, 'Noa': 3}

Adding a condition

You can filter items using an if clause at the end:

{key_expression: value_expressionfor itemin iterableif condition}

Example: keep only even numbers:

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}

Using an if/else expression

If you want the value to change depending on a condition, you can use a conditional expression:

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().

items = [("apple",3), ("banana",5), ("pear",2)]
inventory = {name: countfor name, countin items}

print(inventory)# {'apple': 3, 'banana': 5, 'pear': 2}

Dictionary comprehension vs dict() + loop

You can always build a dictionary using a loop:

names = ["Amir","Lena","Noa"]
lengths = {}

for namein names:
    lengths[name] =len(name)

Dictionary comprehension does the same thing with less code:

lengths = {name:len(name)for namein names}


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:

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:

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:

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:

raw = {"  Email ":"nora@example.com","Name":"Nora"," CITY":"Vienna"}
cleaned = {key.strip().lower(): valuefor key, valuein raw.items()}

print(cleaned)# {'email': 'nora@example.com', 'name': 'Nora', 'city': 'Vienna'}

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:

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.

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.

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.

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.

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.

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:

config = {k: vfor k, vin (line.split("=",1)for linein lines)}


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.

nums = [1,2,3]
as_dict =dict((n, n * n)for nin nums)

The same result is easier to read like this:

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.

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.

Using functions inside comprehension

Comprehensions can call functions, which is great, but don’t cram too much logic into one line.

Readable example:

names = ["  Mina ","  Ravi "," Elena "]
clean = {name.strip().lower():len(name.strip())for namein names}

Hard-to-read example:

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.

Nested loops inside a dictionary comprehension

You can combine loops, but clarity matters.

Example: create a dictionary of (row, col) positions:

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:

data = {"name":"Nora","password":"1234","city":"Vienna"}
safe = {k: vfor k, vin data.items()if k !="password"}

Filter by value:

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:

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():

swapped = {v: kfor k, vin data.items()}
print(swapped)# {1: 'a', 2: 'b'}


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.