Dictionaries — Iteration & Methods
Loop through dictionaries and use built-in methods. 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 Value SwapperStudy Material
Read the full lesson
Keys, values, and items
Dictionaries store pairs, so you often loop through keys, values, or both.
pythonscores = {"Ali": 91, "Mona": 88}
Looping over keys (default)
By default, a for loop gives you keys.
pythonfor name in scores: print(name)
Looping over values
Use values() when you only need the values.
pythonfor score in scores.values(): print(score)
Looping over key and value
Use items() to get both key and value at the same time.
pythonfor name, score in scores.items(): print(name, score)
Building a new dictionary
Create a new dict instead of modifying the one you are looping.
pythoncurved = {} for name, score in scores.items(): curved[name] = score + 5
Safer lookups with get()
get() avoids KeyError when a key may be missing.
pythonprint(scores.get("Sam", 0)) # 0 if missing
setdefault() for grouping
setdefault() creates a list for a key if it is missing.
pythonerrors = {} errors.setdefault("E101", []).append("missing file")
Counting frequencies (classic pattern)
This is a common real-world use of dictionaries.
pythontext = "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().
pythonfor 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 returnNoneif 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()andsetdefault()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.
Value Swapper
Invert a dictionary using iteration.
Frequency Counter
Build a character distribution map.
Filtering by Iteration
Cleanse a dictionary of inactive objects.
Data Aggregation
Group data sequentially utilizing dictionary default values.
Sorting Dict Items by Value
Iterate upon a dictionary sequenced by its values.