Sub topic 6
Looping over nested structures
This chapter assumes you can write a basic for loop, call functions, and read nested data with chained indexing such as students[1]["grades"][2]. It also assumes you know how to change nested values in place. The goal here is to visit every part of a nested structure without errors, and to choose the right loop for each shape of data.
The core idea: one loop per level
A nested structure has levels. A list of dictionaries has two: the list, then each dictionary. Looping over it takes one loop per level. The outer loop picks one item from the outer container. The inner loop picks one item from whatever that item contains.
Before you write a loop, ask two questions at each level:
- What type of container is this? A list gives you values. A dictionary gives you keys, unless you ask for more.
- What do I need from it? Only values, only keys, both, or the position of each item?
The answers decide which of three tools you use: a plain for, items(), or enumerate().
Looping over a dictionary of dictionaries
Iterating a dictionary directly gives its keys. To get keys and values together, call items(). For a dictionary of dictionaries, use items() at each level.
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 unpacks each pair of inventory into category (a string) and items (an inner dictionary). The inner loop then unpacks each pair of that inner dictionary. Naming the variables after what they hold makes the loop easy to read. Names such as k and v hide the structure.
Python dictionaries keep insertion order, so the output follows the order in which keys were added.
Choosing keys(), values(), or items()
| Method | Gives you | Use when |
|---|---|---|
| `for k in d` or `d.keys()` | keys | you only need the names |
| `d.values()` | values | you only need the contents |
| `d.items()` | `(key, value)` pairs | you need both |
For example, to total every count in the inventory above, you only need the values at each level:
inventory = {
"fruit": {"apple": 3, "pear": 0},
"veg": {"kale": 5},
}
total = 0
for items in inventory.values():
for count in items.values():
total += count
print(total) # 8Looping over a list of dictionaries
A list of dictionaries is the most common shape for records, such as rows from a file or items from an API. The outer loop gives you one dictionary per pass.
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
for student in students:
grades = student["grades"]
average = sum(grades) / len(grades)
print(f"{student['name']}: {average:.1f}")
# Ana: 87.5
# Ben: 83.3Here the loop variable student is a dictionary. You read its keys directly, and you can pass student["grades"] to built-in functions such as sum() and len() without a second loop. Use an inner loop only when you need to act on each grade separately.
for student in students:
for grade in student["grades"]:
if grade < 80:
print(student["name"], "has a low grade:", grade)
# Ben has a low grade: 70Looping over a list of lists
A list of lists is often used as a table or grid. The outer loop gives one row. The inner loop gives one cell.
grid = [
[1, 2, 3],
[4, 5, 6],
]
for row in grid:
for cell in row:
print(cell, end=" ")
print()
# 1 2 3
# 4 5 6When each row has the same length and you want to work column by column, zip(*grid) transposes the grid, so that each pass of the loop gives one column.
grid = [
[1, 2, 3],
[4, 5, 6],
]
for column in zip(*grid):
print(column, sum(column))
# (1, 4) 5
# (2, 5) 7
# (3, 6) 9zip stops at the shortest row. If rows have different lengths, the extra cells are silently dropped. Use itertools.zip_longest when you need to keep them.
Using enumerate() when position matters
A plain for loop does not tell you the index of the current item. Beginners often fix this with range(len(...)), which works but is noisy and easy to get wrong. enumerate() gives you the index and the item together.
grid = [
[1, 2, 3],
[4, 5, 6],
]
for r, row in enumerate(grid):
for c, cell in enumerate(row):
if cell % 2 == 0:
print(f"even value {cell} at row {r}, column {c}")
# even value 2 at row 0, column 1
# even value 4 at row 1, column 0
# even value 6 at row 1, column 2Pass start=1 to enumerate() when you want numbering for display, such as enumerate(students, start=1). Do not use that offset as a real list index.
You can combine tools. This loop numbers each student and reads the dictionary at the same time:
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
for number, student in enumerate(students, start=1):
print(number, student["name"], max(student["grades"]))
# 1 Ana 90
# 2 Ben 92Looping over a dictionary of lists
A dictionary of lists maps a name to several values. Use items() for the outer level and a plain loop for the list.
scores = {
"Ana": [90, 85],
"Ben": [70, 88, 92],
}
for name, grades in scores.items():
for grade in grades:
print(name, grade)
# Ana 90
# Ana 85
# Ben 70
# Ben 88
# Ben 92Flattening and filtering with comprehensions
When a loop only collects values into a new list, a comprehension is shorter. Read a nested comprehension in the same order as the nested loops: the outer for comes first.
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
all_grades = [grade for student in students for grade in student["grades"]]
print(all_grades) # [90, 85, 70, 88, 92]
high = [
(student["name"], grade)
for student in students
for grade in student["grades"]
if grade >= 90
]
print(high) # [('Ana', 90), ('Ben', 92)]Keep comprehensions to two for clauses at most. With a third, a regular loop is easier to read and to debug. If the loop has side effects such as printing or updating a counter, use a regular loop as well.
Changing data while looping
Reading while looping is safe. Changing the size of a container while you loop over it is not.
Modifying values: safe
The loop variable refers to the same object as the one in the container. If that object is mutable (a list or dictionary), changing it changes the original.
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
for student in students:
student["grades"].append(100)
print(students[0]["grades"]) # [90, 85, 100]Assigning to the loop variable itself does not change the container, because it only rebinds the name:
numbers = [1, 2, 3]
for n in numbers:
n = n * 10 # changes the local name only
print(numbers) # [1, 2, 3]To replace values in a list, loop over the indexes with enumerate() and assign to the list:
numbers = [1, 2, 3]
for i, n in enumerate(numbers):
numbers[i] = n * 10
print(numbers) # [10, 20, 30]Adding or removing items: unsafe
Removing items from a list while looping over it skips elements, because the later items shift left under the iterator. Adding or removing keys in a dictionary during iteration raises RuntimeError: dictionary changed size during iteration.
numbers = [1, 2, 2, 3]
for n in numbers:
if n == 2:
numbers.remove(n)
print(numbers) # [1, 2, 3] (one 2 was skipped)Two safe patterns avoid the problem. Build a new container, or loop over a copy.
inventory = {
"fruit": {"apple": 3, "pear": 0},
"veg": {"kale": 5},
}
# Build a new structure with only the items in stock
in_stock = {
category: {name: count for name, count in items.items() if count > 0}
for category, items in inventory.items()
}
print(in_stock) # {'fruit': {'apple': 3}, 'veg': {'kale': 5}}
# Or loop over a copy of the keys while deleting from the original
for category, items in inventory.items():
for name in list(items):
if items[name] == 0:
del items[name]
print(inventory) # {'fruit': {'apple': 3}, 'veg': {'kale': 5}}In the second pattern, list(items) makes a separate list of keys, so deleting from items does not disturb the loop. Changing the value for an existing key during iteration is allowed, since the size does not change.
Handling uneven data
Real data is rarely uniform. Some records lack a key, and some lists are empty. Combine looping with the safe access tools from the previous chapter.
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Cy"},
{"name": "Dee", "grades": []},
]
for student in students:
grades = student.get("grades", [])
if grades:
print(student["name"], sum(grades) / len(grades))
else:
print(student["name"], "has no grades")
# Ana 87.5
# Cy has no grades
# Dee has no gradesThe default [] handles the missing key, and the if grades: test handles the empty list. Without that test, sum(grades) / len(grades) would raise ZeroDivisionError for Dee.
Stopping early and skipping
break and continue affect only the innermost loop. This surprises people who expect break to leave both loops.
grid = [
[1, 2, 3],
[4, 5, 6],
]
for row in grid:
for cell in row:
if cell == 2:
break
print("finished row", row)
# finished row [1, 2, 3]
# finished row [4, 5, 6]The break ended the inner loop for the first row only, and the outer loop carried on. To leave both loops, put them in a function and use return. This is usually clearer than flag variables.
def find_cell(grid, target):
for r, row in enumerate(grid):
for c, cell in enumerate(row):
if cell == target:
return r, c
return None
grid = [
[1, 2, 3],
[4, 5, 6],
]
print(find_cell(grid, 5)) # (1, 1)
print(find_cell(grid, 99)) # NoneSeeing the flow of a nested loop
The diagram below shows how control moves in a two-level loop. The inner loop runs to completion for each pass of the outer loop.
If the outer list has 100 items and each holds 100 inner items, the body of the inner loop runs 10,000 times. Nested loops multiply, so avoid putting slow work such as a repeated search inside the innermost loop when a dictionary lookup would do.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ValueError: too many values to unpack` | Unpacking a dictionary without `items()`, or unpacking a row with the wrong number of names | Use `.items()`, and check the shape of the data |
| `TypeError: string indices must be integers` | Looping over keys but treating each key as a record | Loop over `.values()` or `.items()` |
| `KeyError` inside the loop | A record lacks a key | Use `.get()` with a default |
| Items are skipped | Removing from a list during iteration | Build a new list or iterate over a copy |
| `RuntimeError: dictionary changed size` | Adding or deleting keys during iteration | Loop over `list(d)` or build a new dictionary |
| Original data is unchanged after the loop | Assigning to the loop variable | Assign through the index or key instead |
Exercise
Given orders = {"Ana": [{"item": "pen", "qty": 2}, {"item": "ink", "qty": 1}], "Ben": [{"item": "pen", "qty": 5}]}, write loops that print each customer's total quantity, in the form Ana 3. Then explain why replacing the inner loop with del calls on orders["Ana"] during iteration over orders["Ana"] would be a bug.
Show answer
Use items() for the outer level and a running total for the inner list: for name, lines in orders.items():, then total = 0, then for line in lines: total += line["qty"], then print(name, total). This prints Ana 3 and Ben 5. Deleting from orders["Ana"] while looping over that same list shifts the later elements left, so the iterator skips the element that follows each deleted one. Build a new list or loop over a copy such as list(orders["Ana"]) instead.
Exercise
Write a function find_key(data, target) that takes a list of dictionaries and returns the index of the first dictionary whose "id" equals target, or None if no dictionary matches. Why is return better than break here?
Show answer
def find_key(data, target): then for i, record in enumerate(data): then if record.get("id") == target: return i, and return None after the loop. Using .get("id") avoids a KeyError for records without an id. return leaves the function immediately and also gives the caller the result, while break would only leave the current loop and would need extra variables to carry the answer out.