IntermediateLesson firstCategory 8 of 20

Dictionary & Set Comprehensions

Build dicts and sets with comprehension syntax. Read the lesson first, then move through the exercises in order.

8 Sections5 Exercises

After reading

Practice Arena

Begin with the first exercise, then continue step by step through the module.

Start with Data Inversion

Study Material

Read the full lesson

Dictionary comprehension pattern

A dictionary comprehension builds a dict in one pass.

python
squares = {n: n * n for n in range(5)}

Filtering in a dict comprehension

You can include only the items that match a condition.

python
scores = {"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.

python
names = ["Ali", "Mona"] lengths = {name: len(name) for name in names}

Inverting a dictionary

Swap keys and values carefully.

python
original = {"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)

python
text = "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.

python
words = ["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.