Dict & set comprehensions with conditions
Comprehensions beyond lists
Lesson 5 of 20 · 9 min · Module 2: Work with data efficiently
Comprehensions build whole collections in one readable line. The same idea works for dictionaries and sets, not just lists.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Write dict and set comprehensions
- Filter inside a comprehension
- Know when a loop is clearer
The idea
A dict comprehension looks like {key: value for item in items}; a set comprehension like {value for item in items}. Add if at the end to filter. Keep them short: when a comprehension needs several lines, a normal loop is clearer.
scores = {"Ana": 82, "Bob": 45, "Mia": 91}
passed = {name: s for name, s in scores.items() if s >= 50}
print(passed)
01Three kinds of brackets
[x for x in xs] builds a list, {x for x in xs} a set, and {k: v for k, v in pairs} a dict. Parentheses (x for x in xs) build a lazy generator instead.
words = ["sky", "Sea", "sky"]
print({w.lower() for w in words}){'sea', 'sky'}02Filtering
An if at the end keeps only matching items: {n: s for n, s in scores.items() if s >= 50}. Filtering and transforming in one step avoids a temporary list.
03Readability first
A comprehension that fits on one line is easy to read. If you need nested loops, conditions, and side effects, write a regular for loop with clear names.
Your turn
invert(mapping) that turns {"ana": "web", "bob": "data", "mia": "web"} into {"web": ["ana", "mia"], "data": ["bob"]}: each value maps to the sorted list of keys that had it. Also write domains(emails) that returns the set of lowercase domains from a list of email addresses.What the checks look for
- Inverts a mapping with sorted key lists
- Inverts an empty mapping
- Collects lowercase domains once
- Returns a set
Take this with you
Comprehensions are concise for simple transformations; loops are clearer for complex ones.
Go a little further
Rewrite invert with a single loop and dict.setdefault, and compare the readability.