IntermediateLesson firstCategory 4 of 20

Dictionaries — Iteration & Methods

Loop through dictionaries and use built-in methods. Read the lesson first, then move through the exercises in order.

12 Sections5 Exercises

After reading

Practice Arena

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

Start with Value Swapper

Study Material

Read the full lesson

Keys, values, and items

Dictionaries store pairs, so you often loop through keys, values, or both.

python
scores = {"Ali": 91, "Mona": 88}

Looping over keys (default)

By default, a for loop gives you keys.

python
for name in scores: print(name)

Looping over values

Use values() when you only need the values.

python
for score in scores.values(): print(score)

Looping over key and value

Use items() to get both key and value at the same time.

python
for name, score in scores.items(): print(name, score)

Building a new dictionary

Create a new dict instead of modifying the one you are looping.

python
curved = {} for name, score in scores.items(): curved[name] = score + 5

Safer lookups with get()

get() avoids KeyError when a key may be missing.

python
print(scores.get("Sam", 0)) # 0 if missing

setdefault() for grouping

setdefault() creates a list for a key if it is missing.

python
errors = {} errors.setdefault("E101", []).append("missing file")

Counting frequencies (classic pattern)

This is a common real-world use of dictionaries.

python
text = "banana" counts = {} for ch in text: counts[ch] = counts.get(ch, 0) + 1

Sorting keys or items

If you need sorted output, wrap keys or items with sorted().

python
for name in sorted(scores.keys()): print(name)

Do not change size while iterating

Adding or removing keys during a loop can cause errors or skipped items. Build a new dict instead.

Common mistakes to avoid

  • Using keys() when you need both key and value.
  • Forgetting that get() can return None if no default is given.
  • Modifying a dict while looping over it.

What you should understand after this lesson

  • How to loop over keys, values, and items.
  • How to build new dicts from old ones.
  • How to use get() and setdefault() safely.
  • Why changing size during iteration is risky.

Interactive

Exercises for this topic

These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.