Sub topic 12
Knowing when to stop nesting
This chapter assumes you can read and change nested lists and dictionaries, loop over them, and copy them safely. Nesting is a good fit for data that arrives nested, such as JSON. It becomes a problem when you design your own data and keep adding layers.
Warning signs
Nesting has probably gone too far when you see any of these:
- Access chains such as
data["users"][i]["orders"][j]["items"][0]appear in many places. - Readers must remember what each position means. For example,
row[2]is the price, but nothing in the code says so. - The same
.get(...).get(...)guard code is repeated everywhere. - Different parts of the program add keys with slightly different spellings.
- You need to look up the same data in two ways, for example by name and by id, so you keep two nested copies in sync.
A deep structure hides its meaning in the shape of the data. The code that uses it must know that shape, so a change to the shape breaks code in many places.
Option 1: a class or dataclass
If every dictionary has the same keys, you have a record. A dataclass gives each field a name, a type hint, and a default. A misspelled attribute raises an AttributeError immediately, and it can't silently create a new field the way a misspelled dictionary key can.
from dataclasses import dataclass, field
@dataclass
class Student:
name: str
grades: list[int] = field(default_factory=list)
def average(self) -> float:
return sum(self.grades) / len(self.grades) if self.grades else 0.0
students = [Student("Ana", [90, 85]), Student("Ben", [70, 88, 92])]
students[0].grades.append(95)
print(students[0]) # Student(name='Ana', grades=[90, 85, 95])
print(round(students[1].average(), 1)) # 83.3The outer list and the inner grades list are still nested. The change is that the middle layer, the dictionary with fixed keys, became a named type. Behavior such as average() now lives next to the data.
Use field(default_factory=list) for mutable defaults. A plain grades: list[int] = [] is rejected by dataclasses because every instance would share one list, which is the shared reference trap from earlier.
Option 2: a flat list of records
Nesting by category is convenient to read but awkward to query. A flat list stores one record per item, with the category as a field.
rows = [
{"category": "fruit", "name": "apple", "count": 3},
{"category": "fruit", "name": "pear", "count": 0},
{"category": "veg", "name": "kale", "count": 5},
]
fruit_total = sum(r["count"] for r in rows if r["category"] == "fruit")
print(fruit_total) # 3Adding a second grouping, such as "by supplier", means adding a field. It doesn't mean restructuring the data. When you need the nested view, build it from the flat list with defaultdict.
Option 3: tuple keys
For data indexed by two coordinates, a dictionary keyed by tuples replaces a dictionary of dictionaries. Tuples are immutable and hashable, so they work as keys.
grid = {(0, 0): "X", (1, 2): "O"}
print(grid.get((1, 2))) # O
print(grid.get((2, 2), ".")) # .This removes the "does the outer key exist yet?" step, and one get() call is enough.
Other options
| Situation | Better tool |
|---|---|
| Fixed fields, simple record | `dataclass` or `NamedTuple` |
| Many rows, queries and joins | A database such as `sqlite3` |
| Large tables of numbers | pandas or NumPy |
| Two-index lookup | Dictionary with tuple keys |
| Data from an outside source | Keep it nested, then convert it to your own types |
A decision path
A quick rule of thumb
Ask three questions:
- Can you name every level in one word, such as "students", "grades", "score"? If not, the structure is unclear.
- Does the same access chain appear in more than two places? Wrap it in a function or a class.
- Do you copy or guard data at every step? The shape is probably working against you.
Exercise
A program stores orders = {"o1": {"customer": "Ana", "total": 40}, "o2": {"customer": "Ben", "total": 25}}. Every order has the same keys, and you often need all orders for one customer. Which structure would you move to, and why?
Show answer
Use a dataclass Order(id, customer, total) and keep the orders in a flat list. The inner dictionaries all share the same keys, so they are records, and a dataclass catches misspelled fields. The query "all orders for one customer" is a simple filter, [o for o in orders if o.customer == "Ana"]. If you run it often, build a defaultdict(list) grouped by customer from the flat list when you need it.