Sub topic 6
Looping over nested structures
This chapter assumes you can write a for loop, call items() on a dictionary, and read values with chained indexing such as data["a"][0]. It shows how to visit every value in a nested structure, and which loop style fits each shape.
One loop per level
A nested structure needs one loop for each level you want to visit. The inner loop runs completely for each pass of the outer loop.
For a dictionary of dictionaries, use items() at each level. It gives you the key and the value together, so you never need to index back into the dictionary.
inventory = {
"fruit": {"apple": 3, "pear": 0},
"veg": {"kale": 5},
}
for category, items in inventory.items():
for name, count in items.items():
print(category, name, count)
# fruit apple 3
# fruit pear 0
# veg kale 5The outer loop binds items to the inner dictionary. The inner loop then iterates over that dictionary.
Lists of dictionaries
A list of dictionaries is the most common shape, for example rows loaded from a file or an API. Loop over the list, then read keys from each dictionary.
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
for student in students:
average = sum(student["grades"]) / len(student["grades"])
print(f"{student['name']}: {average:.1f}")
# Ana: 87.5
# Ben: 83.3Here only one loop is needed. The inner list is handled by sum() and len(), so you loop only when you need to act on each grade separately.
Using enumerate() for positions
When you need the index as well as the value, use enumerate(). It yields (index, value) pairs. Pass start=1 for human-friendly numbering.
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
for s_index, student in enumerate(students):
for g_index, grade in enumerate(student["grades"], start=1):
print(f"{student['name']} exam {g_index}: {grade}")
# Ana exam 1: 90
# Ana exam 2: 85
# Ben exam 1: 70
# Ben exam 2: 88
# Ben exam 3: 92The unused s_index is harmless, but if you do not need it, drop the outer enumerate(). Avoid for i in range(len(students)) and then students[i]. Looping over the items directly is shorter and less error-prone.
Lists of lists
A grid is a list of lists. Two loops visit each cell, and enumerate() gives you the row and column positions.
grid = [
[1, 2, 3],
[4, 5, 6],
]
for row_number, row in enumerate(grid):
for col_number, value in enumerate(row):
print(row_number, col_number, value)
total = sum(value for row in grid for value in row)
print(total) # 21The generator expression in the last lines reads in the same order as the loops: for row in grid comes first, then for value in row.
Choosing a loop style
| Shape | Typical loop |
|---|---|
| List of dicts | `for item in rows:` then read keys |
| Dict of lists | `for key, values in d.items():` then `for v in values:` |
| Dict of dicts | `for k, inner in d.items():` then `for k2, v in inner.items():` |
| List of lists | `for row in grid:` then `for cell in row:` |
Common errors
- Changing the size of a collection while looping over it. Adding or removing keys during
for key in d:raisesRuntimeError: dictionary changed size during iteration. Loop overlist(d)orlist(d.items())if you must change the keys. For lists, build a new list instead of removing items during the loop. - Looping over a dictionary and expecting values.
for x in dyields keys. Used.values()ord.items(). - Assuming every item has the same shape. If some dictionaries lack a key,
item["key"]raisesKeyError. Useitem.get("key", default)as covered in the previous chapter on safe access. - Rebinding the loop variable. Writing
grade = grade + 1insidefor grade in grades:changes only the local name. To change the list, assign by index:grades[i] = grades[i] + 1.
Changing values in place is safe during a loop, because the size does not change. This example curves every grade by 5 points, capped at 100.
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
for student in students:
for i, grade in enumerate(student["grades"]):
student["grades"][i] = min(grade + 5, 100)
print(students[1]["grades"]) # [75, 93, 97]Exercise
Given scores = {"math": [90, 80], "art": [70]}, write loops that print each subject with its average, for example math 85.0. Why does for subject in scores alone not give you the lists?
Show answer
Use for subject, values in scores.items(): print(subject, sum(values) / len(values)). Iterating over a dictionary directly yields only its keys, so you would have to look up scores[subject] yourself. items() gives the key and the list together.
Exercise
This code raises an error. What is it, and how do you fix it? inventory = {"apple": 0, "pear": 2} for name, count in inventory.items(): if count == 0: del inventory[name]
Show answer
It raises RuntimeError: dictionary changed size during iteration, because a key is deleted while the dictionary is being iterated. Loop over a copy of the items, for name, count in list(inventory.items()):, or build a new dictionary with a comprehension such as {n: c for n, c in inventory.items() if c != 0}.