Lesson 21 of 34 · Dictionaries & Sets
Python Dictionary and Set Comprehensions
You already know list comprehensions. Python offers the same compact syntax for building dictionaries and sets — perfect for transforming, filtering and reshaping data in a single readable line.
Dict comprehensions
A dict comprehension looks like a list comprehension with curly braces and a key: value pair in front:
squares = {n: n * n for n in range(1, 5)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16}
heroes = ["Ada", "Bo", "Cyrus"]
name_lengths = {name: len(name) for name in heroes}
print(name_lengths) # {'Ada': 3, 'Bo': 2, 'Cyrus': 5}
Transforming an existing dictionary
Loop over .items() to get each key and value, then build new pairs:
prices = {"potion": 5, "rope": 2, "map": 15}
doubled = {item: price * 2 for item, price in prices.items()}
# {'potion': 10, 'rope': 4, 'map': 30}
labels = {item.upper(): f"{price} gold" for item, price in prices.items()}
# {'POTION': '5 gold', 'ROPE': '2 gold', 'MAP': '15 gold'}
Filtering
Add an if clause to keep only some pairs:
scores = {"Ada": 98, "Bo": 45, "Cy": 72}
passed = {name: score for name, score in scores.items() if score >= 60}
# {'Ada': 98, 'Cy': 72}
Building a dictionary from two lists
zip() walks through two sequences side by side, producing pairs (you'll explore it fully in Chapter 6):
names = ["Ada", "Bo"]
levels = [7, 3]
roster = {name: level for name, level in zip(names, levels)}
# {'Ada': 7, 'Bo': 3}
For a plain pairing like this, dict(zip(names, levels)) does the same job.
Inverting a dictionary
Swapping keys and values is a one-liner:
codes = {"fire": "F", "ice": "I"}
by_code = {code: element for element, code in codes.items()}
# {'F': 'fire', 'I': 'ice'}
If two keys share the same value, only the last one survives — keys must be unique.
Set comprehensions
Use curly braces without a colon to build a set. Duplicates vanish automatically:
words = ["apple", "avocado", "banana", "cherry"]
first_letters = {w[0] for w in words}
print(first_letters) # {'a', 'b', 'c'} (order may vary)
lengths = {len(w) for w in words if w.startswith("a")}
print(lengths) # {5, 7}
Choosing the right brackets
| Syntax | Builds |
|---|---|
[x for x in data] |
list |
{x for x in data} |
set |
{k: v for k, v in data} |
dictionary |
(x for x in data) |
generator — a lazy sequence, covered in Chapter 6 |
Common mistakes
{}is an empty dictionary, never an empty set — even though set comprehensions use curly braces.- Silent overwrites: a dict comprehension that produces the same key twice keeps only the last value.
- Forgetting
.items():{k: v for k, v in prices}loops over the keys only and tries to unpack each string into two variables — usually failing withValueError: too many values to unpack. - Over-long comprehensions: if it no longer fits on a line or two, switch to a regular loop.
Assignment
Write three functions, each with a single comprehension:
word_lengths(words)returns a dictionary mapping every word to its length.affordable(prices, budget)returns a new dictionary with only the items whose price is less than or equal tobudget.initials(names)returns a set of the uppercase first letters of the names, skipping empty strings.
word_lengths(["hiss", "serpent"]) # {"hiss": 4, "serpent": 7}
affordable({"potion": 5, "sword": 120, "map": 15}, 20) # {"potion": 5, "map": 15}
initials(["ada", "Bo", "alan", ""]) # {"A", "B"}Premium lesson
Unlock the full Learn Python course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .