Sub topic 12
Knowing when to stop nesting
This chapter assumes you can read, update, copy and loop over nested lists and dictionaries, and that you know get(), defaultdict, copy.deepcopy() and the json module from earlier chapters. Here you will learn to recognize when a nested structure has stopped helping and what to use in its place.
Why nesting has a limit
Nested lists and dictionaries are quick to write. You need no class definitions, the structure maps directly onto JSON, and you can print it to inspect it. These strengths hold up for small data and for data you receive from outside, such as an API response.
The costs grow with depth and with the length of the program's life:
- Keys are unchecked strings. A typo such as
"quantity"instead of"qty"fails only when that line runs. - The shape lives in your head. Nothing in the code says which keys must exist or what type their values have.
- Access gets long. An expression like
order["customer"]["address"]["city"]repeats the shape of the data at every use. - Defensive code spreads. Every access path needs its own
get()chain ortry/except. - Copying costs more. A
deepcopy()of a large structure is slow, and a forgotten deep copy causes aliasing bugs. - Changes ripple. Renaming a key means finding every string that mentions it.
Nesting is a poor fit when the same shape appears in many places, when the data has fixed fields and behavior, or when you query it in several different ways.
Warning signs
Look for these signals in your own code:
- You write a comment above a variable to explain what each level means.
- You have more than about three levels of chained indexing in the same expression.
- The same
data["a"]["b"][0]["c"]path appears in several functions. - Every function that receives the structure starts by checking which keys exist.
- You keep a second structure in sync with the first, such as a list of names that must match the keys of a dictionary.
- You search a list of dictionaries with a loop to find one record by
id, and you do it often.
Option 1: a class or dataclass for records with fixed fields
If every item has the same known fields, you have a record. Records belong in a class. A dataclass gives you named attributes, an automatic __init__, a readable repr and equality comparison.
Here is a nested version of an order:
order = {
"customer": "Ana",
"lines": [
{"sku": "A1", "qty": 2, "price": 3.5},
{"sku": "B2", "qty": 1, "price": 10.0},
],
}
total = sum(line["qty"] * line["price"] for line in order["lines"])
print(total) # 17.0Here is the same data as dataclasses, with the calculation moved next to the data it uses:
from dataclasses import dataclass, field
@dataclass
class Line:
sku: str
qty: int
price: float
@property
def total(self) -> float:
return self.qty * self.price
@dataclass
class Order:
customer: str
lines: list[Line] = field(default_factory=list)
def total(self) -> float:
return sum(line.total for line in self.lines)
order = Order("Ana", [Line("A1", 2, 3.5), Line("B2", 1, 10.0)])
print(order.total()) # 17.0
print(order.lines[0]) # Line(sku='A1', qty=2, price=3.5)The collections are still there: lines is a list. You have not removed nesting. You have replaced the inner dictionaries, which had unchecked keys, with objects that have declared fields.
A misspelled attribute raises AttributeError right away, and editors and type checkers flag it before you run the program. A misspelled dictionary key is only a string, so nothing catches it until that line executes.
Use field(default_factory=list) for mutable defaults. Writing lines: list[Line] = [] is rejected by dataclass for this reason: it is the shared-reference trap from earlier, applied to class definitions.
Copying dataclasses
The copy rules do not change. copy.copy() and dataclasses.replace() make shallow copies, so the new object shares its lines list with the original. Use copy.deepcopy() when you need full independence. The same cost and the same aliasing risks apply.
Option 2: a lighter record type
Sometimes a class is more than you need. Two lighter choices exist.
typing.NamedTuple gives an immutable record with named fields, which is useful for small values that you never change, such as a coordinate:
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
p = Point(3, 4)
print(p.x, p[1]) # 3 4typing.TypedDict describes the keys of a dictionary for a type checker. At runtime it is an ordinary dict, so nothing is enforced when the program runs:
from typing import TypedDict
class Student(TypedDict):
name: str
grades: list[int]
ana: Student = {"name": "Ana", "grades": [90, 85]}
print(ana["grades"][0]) # 90TypedDict fits best when you must keep dictionaries, for example because the data comes from json.loads() and goes straight back to JSON, and you still want a checker to catch wrong keys.
Option 3: flatten the structure
Depth often comes from a habit, not a need. Two flat designs replace common nesting patterns.
Tuple keys instead of a list of lists. A sparse grid stored as a list of lists wastes space and invites the [[0] * 3] * 2 bug. A dictionary keyed by (row, column) stores only the cells that exist:
grid = {(0, 0): "X", (2, 1): "O"}
print(grid.get((1, 1), ".")) # .
grid[(1, 1)] = "X"
print(sorted(grid)) # [(0, 0), (1, 1), (2, 1)]Tuples work as keys because they are immutable and hashable, provided every element in them is hashable too.
A record list plus an index. If you often look up one record by a field, building a dictionary once beats looping every time:
users = [
{"id": 7, "name": "Ana"},
{"id": 9, "name": "Ben"},
]
by_id = {user["id"]: user for user in users}
print(by_id[9]["name"]) # Ben
by_id[9]["name"] = "Benjamin"
print(users[1]["name"]) # BenjaminThe last two lines show the trade-off. by_id holds references to the same inner dictionaries as users, so one change shows up in both views. That is useful, because there is only one copy of each record. It becomes a bug if you add or remove records in only one of the two containers. Whoever owns the data must update the list and the index together, which is a good reason to wrap both in a small class.
Option 4: a real query tool
When you slice the same data many ways, such as grouping, filtering, sorting and aggregating, a nested dictionary forces you to write a loop for each question. A table-shaped tool answers these questions directly. The standard library includes sqlite3, which can run in memory:
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE grades (student TEXT, score INTEGER)")
conn.executemany(
"INSERT INTO grades VALUES (?, ?)",
[("Ana", 90), ("Ana", 85), ("Ben", 70)],
)
query = "SELECT student, AVG(score) FROM grades GROUP BY student ORDER BY student"
for student, average in conn.execute(query):
print(student, average)
# Ana 87.5
# Ben 70.0Always pass values through ? placeholders, as the INSERT does, and never build SQL by joining strings. For large numeric tables, third-party libraries such as pandas fill the same role. For data that must survive between runs and be shared, a database is the natural next step.
Choosing between them
The same decision as a table:
| Situation | Better choice | Reason |
|---|---|---|
| Data from `json.loads()` used once and thrown away | Nested dict and list | Conversion code would cost more than it saves |
| Same record shape used across modules | `dataclass` | Declared fields, one place to rename |
| Immutable small value | `NamedTuple` | Hashable, tuple-like, named fields |
| Must stay a dict for JSON, but needs checking | `TypedDict` | Type checker catches wrong keys, no runtime cost |
| Sparse grid | Dict with tuple keys | No wasted cells, no shared-row bug |
| Frequent lookup by one field | Dict index | Constant-time lookup instead of a scan |
| Many grouping and filtering questions | `sqlite3` or pandas | Queries replace hand-written loops |
Failure modes when you leave nesting
Replacing nesting is not free either.
- Too many tiny classes. A class for a structure used in one function adds code without adding clarity. If the nested dictionary is local, short and obvious, keep it.
- Duplicated state. A list plus an index can drift apart. Keep one source of truth and derive the other.
- Lost JSON simplicity.
json.dumps()cannot serialize a dataclass directly. Convert it first withdataclasses.asdict(), which recursively turns dataclasses into dictionaries and lists. Converting back requires code that you write. - Mixed styles. A codebase where half the records are dictionaries and half are objects is harder to read than one that picked either. Convert at the boundary, where data enters your program, and use one style inside.
A practical rule
Keep nesting at the edges of a program, where data arrives in the shape someone else chose. Convert it to a clearer structure once, near the entrance, and pass that structure through the rest of your code. When the conversion code is longer than the code that uses the data, the data was not worth converting.
Exercise
A function reads settings["servers"][i]["limits"]["cpu"] in six places, and a teammate misspells "limits" as "limit" in one of them. Which two changes remove this class of bug, and why does the bug survive with plain dictionaries?
Show answer
Define the server settings as a dataclass (or TypedDict if the data must stay a dict), with limits and cpu declared as fields. Then convert the loaded data once at the entry point and use attribute access afterward. With plain dictionaries the key is just a string, so a misspelling is legal Python and fails only when that line runs with a KeyError. With a dataclass the misspelled attribute raises AttributeError immediately and is flagged by editors and type checkers before the program runs.
Exercise
You build by_id = {u["id"]: u for u in users} and then run users.append({"id": 12, "name": "Cy"}). What does by_id[12] do, and what does this show about indexes over a list of records?
Show answer
It raises KeyError, because the dictionary was built once and does not follow later changes to the list. The index holds references to the same inner dictionaries, so edits to an existing record appear in both. Adding or removing records does not. Whoever owns the data must update both together, ideally inside one class with methods like add_user().
Exercise
You need the average score per student from thousands of (student, score) rows, then the top five students, then the same data grouped by month. Why is a nested dictionary a weak fit, and what would you use?
Show answer
Each new question needs a new hand-written loop and a new intermediate structure, and the code duplicates grouping logic. A table-oriented tool such as sqlite3 (standard library) or pandas answers each question with a short query, and the data is stored once in a uniform shape.