Sub topic 2
Common ways to nest data
What this chapter covers
This chapter assumes you can create lists and dictionaries, index a list, look up a dictionary key, and write a for loop. The earlier refresher covered those basics.
Nesting means putting a container inside another container. A list can hold dictionaries, a dictionary can hold lists, and so on. Four combinations cover most real programs, and each answers a different kind of question. Choosing the right one early makes the later code (reading, updating, looping) shorter and less error-prone.
The four shapes are:
- a list of dictionaries
- a dictionary of lists
- a dictionary of dictionaries
- a list of lists
This chapter shows what each looks like, when it fits, and what usually goes wrong. Later chapters cover the mechanics of reading and changing the data in detail, so the access code here stays minimal.
A list of dictionaries: a table of records
A list of dictionaries is the most common shape in everyday Python. Each dictionary is one record, such as a user, an order, or a row from a database. The list keeps the records in order.
users = [
{"id": 1, "name": "Ana", "active": True},
{"id": 2, "name": "Ben", "active": False},
{"id": 3, "name": "Caro", "active": True},
]
active_names = [user["name"] for user in users if user["active"]]
print(active_names) # ['Ana', 'Caro']
print(len(users)) # 3Use this shape when:
- you have many items of the same kind
- each item has several named fields
- order matters, or you mostly process every item in turn
The shape is also what you get from most web APIs and from csv.DictReader, so you will meet it often.
Its weakness is lookup. To find the user with id 2, Python has to scan the list from the start and check each dictionary. That is fine for a few hundred records. It becomes slow if you do it repeatedly on a large list.
A dictionary of lists: many values per key
A dictionary of lists maps each key to a collection of values. Use it when one label owns several items and you want to reach the group by its label.
grades = {
"Ana": [90, 85],
"Ben": [70, 88, 92],
}
averages = {name: round(sum(scores) / len(scores), 1) for name, scores in grades.items()}
print(averages) # {'Ana': 87.5, 'Ben': 83.3}Typical uses are:
- grouping items by category, such as words by first letter
- keeping a history of readings per sensor
- an index that maps a word to the pages where it appears
The lists in this shape can have different lengths, as Ana's and Ben's do above. That is usually the point. Be careful with empty lists, though. sum(scores) / len(scores) raises ZeroDivisionError when a student has no grades yet, so decide how your code should treat that case.
A dictionary of dictionaries: lookup by key, then by field
A dictionary of dictionaries combines the record idea with fast lookup. The outer dictionary is keyed by something unique, such as an ID, and each value is a record.
products = {
"A100": {"name": "Lamp", "price": 25.0, "stock": 4},
"B205": {"name": "Desk", "price": 140.0, "stock": 0},
}
print(products["A100"]["price"]) # 25.0
print("B205" in products) # TrueUse this shape when you look up single records by a unique key far more often than you process all of them. Dictionary lookup takes roughly constant time no matter how many records exist. It also prevents duplicates by construction, because a key can appear only once.
Two limits apply:
- The key is stored once, outside the record. If you also want it inside (for example when you pass a record to another function), you must copy it in yourself or pass the key alongside.
- Dictionaries in Python 3.7 and later keep insertion order, but they offer no position-based access such as "the third product". If you need positions, use a list.
You can convert between the first and third shapes. A dictionary comprehension turns a list of records into a keyed lookup table:
users = [
{"id": 1, "name": "Ana"},
{"id": 2, "name": "Ben"},
]
by_id = {user["id"]: user for user in users}
print(by_id[2]["name"]) # BenIf two records share an id, the later one silently replaces the earlier one. When IDs are supposed to be unique, check that before you build the table, for example by comparing len(by_id) with len(users).
A list of lists: rows and columns
A list of lists represents a grid. Each inner list is a row, and the position inside it is the column.
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
print(grid[1][2]) # 6
print([row[1] for row in grid]) # [2, 5, 8] (the middle column)
print(list(zip(*grid))) # [(1, 4, 7), (2, 5, 8), (3, 6, 9)]The first index picks the row and the second picks the column. Reading a row is easy (grid[1]). Reading a column takes a comprehension, or zip(*grid) to flip rows and columns.
Use this shape for:
- game boards and maps
- matrices and small tables of numbers
- any data where position carries the meaning
Two edge cases matter:
- Python does not require inner lists to have the same length. A list such as
[[1, 2], [3]]is valid but "ragged", and code that assumes a rectangle will raiseIndexErroron it. - Creating a grid with
[[0] * 3] * 2gives rows that are the same list object. A later chapter explains this trap in detail. For now, build grids with a comprehension:[[0] * 3 for _ in range(2)].
Mixed nesting and deeper levels
The four shapes combine freely. Real data often has three or more levels. For example, an order can be a dictionary that contains a customer dictionary and a list of item dictionaries:
order = {
"id": 1001,
"customer": {"name": "Ana", "email": "[email protected]"},
"items": [
{"sku": "A100", "qty": 2},
{"sku": "B205", "qty": 1},
],
}
print(order["customer"]["name"]) # Ana
print(order["items"][1]["sku"]) # B205To read this structure, take one step per level. order["items"] gives a list, [1] gives a dictionary, and ["sku"] gives a string. When you design a structure like this, ask at each level: "Do I need names here, or positions?" Fields with names belong in a dictionary. A sequence of similar things belongs in a list.
The diagram below turns that question into a decision path for the first level.
Comparing the shapes
| Shape | Typical question | Finding one item | Main risk |
|---|---|---|---|
| List of dicts | "Which records match this condition?" | Scan the list | Slow repeated lookups |
| Dict of lists | "What belongs to this label?" | Direct by key | Empty or missing lists |
| Dict of dicts | "What are the details for this ID?" | Direct by key | Duplicate keys overwrite |
| List of lists | "What is at this row and column?" | Direct by index | Ragged rows, shared rows |
Keys that are not strings
Dictionary keys must be hashable, which means they must be immutable values such as strings, numbers, and tuples. Lists and dictionaries cannot be keys. A tuple key is a useful alternative to a nested dictionary when the natural key has two parts:
board = {(0, 0): "X", (1, 1): "O"}
print(board[(1, 1)]) # O
print(board.get((2, 2), ".")) # .This stores only the occupied squares. A list of lists would store every square, including the empty ones. Use a tuple-keyed dictionary for sparse data, where most positions are empty. Use a list of lists for dense data, where most positions hold a value.
Trying to use a list as a key fails right away:
try:
lookup = {[0, 0]: "X"}
except TypeError as err:
print(err) # unhashable type: 'list'Common errors when choosing a shape
These mistakes appear again and again:
- Records with different keys. If one dictionary has
"name"and another has"full_name", every access has to guess which one exists. Pick one set of keys and use it everywhere. Missing optional fields are handled in a later chapter. - A list of dictionaries used as a lookup table. If your code contains
for u in users: if u["id"] == wanted:in many places, build a dictionary keyed byidonce and reuse it. - Parallel lists instead of records. Keeping
names = [...]andages = [...]in step is fragile, because inserting or removing in one list but not the other misaligns them. A list of dictionaries keeps each person's fields together. - Going too deep too early. A structure such as
data["a"][0]["b"][2]["c"]is hard to read and hard to change. The last chapter of this tutorial discusses when to switch to a class. - Using a list where a dictionary's names would document the data.
["Ana", 31, True]says nothing about what each position means.{"name": "Ana", "age": 31, "active": True}does.
Check your understanding
Exercise
You have a list of 50,000 product dictionaries, each with a unique "sku" key, and your program looks up one product by SKU thousands of times. Which shape should you convert to, and how do you do it in one line?
Show answer
Convert to a dictionary of dictionaries keyed by SKU: by_sku = {p["sku"]: p for p in products}. Each lookup then takes roughly constant time instead of scanning the whole list. Check that len(by_sku) == len(products) to confirm the SKUs really were unique.
Exercise
A tic-tac-toe board is stored as [["X", "", ""], ["", "O", ""], ["", "", ""]]. Write an expression that returns the diagonal from the top left to the bottom right.
Show answer
[board[i][i] for i in range(3)] returns ['X', 'O', '']. The same index picks the row and the column, which walks the diagonal.