Iterating Over Dicts
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Introduction to Dictionary Iteration
Now that we know how to create, access, and modify dictionaries, let's learn how to loop through them! There are three main ways to iterate through a dictionary in Python.
When you use a for loop with a dictionary directly, Python iterates over the keys by default:
codemon_stats = {"name": "Aquachu", "type": "water", "level": 15, "power": 75}
# Iterating over keys (default behavior)
print("Keys in the dictionary:")
for key in codemon_stats:
print(key)Notice that the loop gives us only the keys, not the values. To access the values, we need to use the key inside the loop.
codemon_stats = {"name": "Aquachu", "type": "water", "level": 15, "power": 75}
# Accessing values using keys in the loop
print("\nKeys and their values:")
for key in codemon_stats:
print(f"{key}: {codemon_stats.get(key)}")Exercise 2 — Three Ways to Iterate: keys(), values(), items()
Python dictionaries provide three methods specifically for iteration. Let's explore each one:
Method 1: .keys() - Explicitly iterate over keys (like we saw before)
codemon = {"name": "Pyrochu", "type": "fire", "level": 18}
print("Using .keys():")
for key in codemon.keys():
print(key)Method 2: .values() - Iterate over values only (ignoring keys)
codemon = {"name": "Pyrochu", "type": "fire", "level": 18}
print("Using .values():")
for value in codemon.values():
print(value)Method 3: .items() - Iterate over key-value pairs together
codemon = {"name": "Pyrochu", "type": "fire", "level": 18}
print("Using .items():")
for key, value in codemon.items():
print(f"{key}: {value}")When to use each method
Use .keys() when you only need the keys (though for key in dict: works too).
Use .values() when you only need the values and don't care about the keys.
Use .items() when you need both keys and values - this is the most common!
Exercise 3 — What Does This Loop Return?
Given the following code, what will be printed?
codemon = {"name": "Florachu", "type": "plant", "level": 20}
for item in codemon.values():
print(item)Florachu
plant
20name
type
levelname: Florachu
type: plant
level: 20('name', 'Florachu')
('type', 'plant')
('level', 20)Hint : Remember what .values() returns - it gives you only the values from the dictionary, not the keys.
Exercise 4 — Complete the Items Loop
Complete the code to iterate through all key-value pairs and print them in the format "key: value".
Hint : Think about which dictionary method returns both keys and values as pairs, and how to unpack those pairs in a for loop.
Exercise 5 — Match Iteration Methods to Use Cases
Match each dictionary iteration method with its best use case:
for key in dict:for value in dict.values():for key, value in dict.items():for key in dict.keys():Exercise 6 — Understanding items() Unpacking
What does the following code demonstrate?
stats = {"hp": 100, "attack": 75}
for stat_name, stat_value in stats.items():
print(f"{stat_name}: {stat_value}")Hint : Look at how the for loop uses two variable names and what .items() returns from a dictionary.
Exercise 7 — Filter Codémons by Level
Complete the code to find and print all Codémon names that have a level greater than 15.
Hint : You need both the name and level to check the condition. Think about which method gives you both pieces of information.
Exercise 8 — Common Dictionary Iteration Patterns
Now let's look at some practical patterns you'll use frequently when iterating through dictionaries:
Pattern 1: Calculating totals
# Sum all values in a dictionary
codemon_counts = {"Aquachu": 5, "Pyrochu": 3, "Florachu": 7}
total_codemons = 0
for count in codemon_counts.values():
total_codemons += count
print(f"Total Codémons: {total_codemons}")Pattern 2: Building a new dictionary
# Create a new dictionary with modified values
original_levels = {"Aquachu": 10, "Pyrochu": 15}
leveled_up = {}
for name, level in original_levels.items():
leveled_up[name] = level + 5
print("After leveling up:", leveled_up)Pattern 3: Conditional filtering
# Find all items that meet a condition
codemon_types = {"Aquachu": "water", "Pyrochu": "fire", "Florachu": "plant", "Zap": "electric"}
water_codemons = []
for name, type in codemon_types.items():
if type == "water":
water_codemons.append(name)
print("Water type Codémons:", water_codemons)Dictionary comprehension preview
Python has a more concise way to create new dictionaries called "dictionary comprehension", but we'll learn that later. For now, focus on understanding these basic iteration patterns!
Exercise 9 — Fix the Iteration Bug
What's wrong with this code?
codemon = {"name": "Aquachu", "level": 10}
for item in codemon:
print(f"Key: {item[0]}, Value: {item[1]}")for item in codemon only gives keys, not key-value pairs. Should use .items()Hint : Think about what happens when you iterate through a dictionary without using a specific method. What does the loop variable contain?
Exercise 10 — Build a Codémon Battle Summary
Complete the code to display a battle summary showing each Codémon's name and whether they won (if wins > 0).
Hint : You need to access both the Codémon name and the number of wins. Think about which iteration method provides both pieces of information.
Exercise 11 — Challenge: Battle Records Analysis
Analyze your Codémon team's battle records using dictionary iteration!
1. Calculate the total number of battles won by all Codémons combined
2. Check if "Rockachu" is in your team
3. Find and print the name of the Codémon with the most wins
battle_records = {"Aquachu": 8, "Pyrochu": 15, "Florachu": 12, "Zap": 6}
print("=== BATTLE RECORDS ANALYSIS ===")
# 1. Calculate total battles won
# 2. Check if 'Rockachu' is in the team
# 3. Find the Codémon with the most wins