Course Progress37%
🍎 Python Basics Topic 37 / 100
⏳ 7 min read

Dict Comprehensions

Build dictionaries in one line — the same power as list comprehensions, applied to key-value pairs.

"If list comprehensions build lists fast, dict comprehensions build dictionaries fast. Same idea, curly braces, and a colon."

— ShurAI

Syntax — Spot the Difference

List comprehension
[expr for x in items]
Dict comprehension
{key:val for x in items}

The only differences: curly braces {} instead of [], and you write key: value instead of just an expression.

Basic Examples

python
# Number → its square
squares = {n: n**2 for n in range(1, 6)}
print(squares)
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Word → its length
words   = ["python", "is", "great"]
lengths = {w: len(w) for w in words}
print(lengths)
# {'python': 6, 'is': 2, 'great': 5}

# Name → name in uppercase
names = ["riya", "arjun", "sneha"]
upper = {n: n.upper() for n in names}
print(upper)
# {'riya': 'RIYA', 'arjun': 'ARJUN', 'sneha': 'SNEHA'}

From Two Lists Using zip()

A very common pattern — combine two parallel lists into one dictionary:

python
names  = ["Riya", "Arjun", "Sneha"]
scores = [88, 75, 92]

gradebook = {name: score for name, score in zip(names, scores)}
print(gradebook)
# {'Riya': 88, 'Arjun': 75, 'Sneha': 92}

With a Condition — Filter Entries

python
all_scores = {"Riya": 88, "Arjun": 55, "Sneha": 92, "Dev": 61}

# Only students who passed (score >= 70)
passed = {name: score for name, score in all_scores.items() if score >= 70}
print(passed)
# {'Riya': 88, 'Sneha': 92}

# Apply a grade label
def grade(s):
    return "A" if s >= 85 else "B" if s >= 70 else "C"

graded = {name: grade(score) for name, score in all_scores.items()}
print(graded)
# {'Riya': 'A', 'Arjun': 'C', 'Sneha': 'A', 'Dev': 'C'}

Real Example — Product Price Lookup

python
products = ["Rice", "Dal", "Milk", "Eggs"]
prices   = [280,   120,  60,    96  ]

# Build lookup dict in one line
shop = {p: c for p, c in zip(products, prices)}

# Apply 10% discount to items over Rs.100
discounted = {
    item: round(price * 0.9)
    for item, price in shop.items()
    if price > 100
}
print(discounted)   # {'Rice': 252, 'Dal': 108}

"Dict comprehensions shine when transforming data — turning a list into a lookup table, filtering entries, or reshaping a dictionary in one clean line."

— ShurAI

🧠 Quiz — Q1

What does {x: x**2 for x in range(3)} produce?

🧠 Quiz — Q2

How do dict comprehensions differ from list comprehensions in syntax?

🧠 Quiz — Q3

What does {n: n*2 for n in [1,2,3] if n > 1} produce?

🧠 Quiz — Q4

What built-in function is commonly used with dict comprehensions to loop over key-value pairs?