Dictionary & Set Comprehensions
Build dicts and sets with comprehension syntax. Read the lesson first, then move through the exercises in order.
After reading
Practice Arena
Begin with the first exercise, then continue step by step through the module.
Start with Data InversionStudy Material
Read the full lesson
Dictionary comprehension pattern
A dictionary comprehension builds a dict in one pass.
pythonsquares = {n: n * n for n in range(5)}
Filtering in a dict comprehension
You can include only the items that match a condition.
pythonscores = {"A": 95, "B": 70, "C": 88} passed = {k: v for k, v in scores.items() if v >= 80}
Transforming keys or values
You can change keys, values, or both.
pythonnames = ["Ali", "Mona"] lengths = {name: len(name) for name in names}
Inverting a dictionary
Swap keys and values carefully.
pythonoriginal = {"a": 1, "b": 2} inverted = {v: k for k, v in original.items()}
If two keys share the same value, the last one wins.
Frequency maps (simple version)
pythontext = "banana" counts = {ch: text.count(ch) for ch in set(text)}
This is fine for small strings. For large data, a loop is faster.
Set comprehensions
Use a set comprehension when you want unique results.
pythonwords = ["hello", "hi", "world"] lengths = {len(w) for w in words}
Common mistakes to avoid
- Forgetting to use
items()when you need keys and values. - Inverting a dict without thinking about duplicates.
- Using a list comprehension when you want a dict or set.
What you should understand after this lesson
- How to build dicts and sets with comprehensions.
- How to filter and transform data in one line.
- When a comprehension is helpful and when it is not.
Interactive
Exercises for this topic
These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.
Data Inversion
Construct a dictionary comprehension substituting standard iterations.
Mapping Functions
Run numerical translations against existing dictionaries dynamically.
Filter Dictionaries
Incorporate `if` assertions deeply within comprehensions.
List-to-Dictionary Sequence
Generate key representations on the fly leveraging data iterators.
Nested Dictionary Compression
Build profound data representations in tight spaces.