Sub topic 3
Reaching into nested data
What this chapter assumes
You should be comfortable with basic Python syntax and variables, indexing lists, looking up dictionary keys, and writing simple for loops and functions. The previous chapter described the common nesting shapes: list of dicts, dict of lists, dict of dicts, and list of lists. This chapter covers reading values out of those shapes. Changing values, handling missing keys safely, and looping are covered in later chapters. Here we only touch on them where they help you read code.
The working model: one lookup per level
Python has no special syntax for nested data. A chained expression such as students[1]["grades"][2] is a series of ordinary lookups. Python evaluates it from left to right. Each [...] applies to the value produced by the part before it.
Two consequences follow from this model:
- Every step must be valid for the type of the value it receives. A list wants an integer or slice, and a dictionary wants a key it contains.
- Every step produces a real value that you could store in a variable. The chain is just a way to skip naming the in-between values.
Reading a list of dictionaries that hold lists
Start with the data from the chapter's main example:
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
print(students[1]["grades"][2]) # 92Here is the same lookup, one level at a time:
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
second = students[1]
print(second) # {'name': 'Ben', 'grades': [70, 88, 92]}
grades = second["grades"]
print(grades) # [70, 88, 92]
print(grades[2]) # 92
print(students[1]["grades"][2]) # 92The two forms give the same result. To write a chain, work from the outside in. Ask what the outermost container is, which element you want from it, and what that element contains.
A deeper structure follows the same pattern. Here the path has five steps:
company = {
"name": "Acme",
"teams": [
{
"name": "Core",
"members": [
{"name": "Ana", "skills": ["python", "sql"]},
{"name": "Ben", "skills": ["go"]},
],
},
],
}
print(company["teams"][0]["members"][1]["skills"][0]) # go
print(company["teams"][0]["members"][0]["skills"][-1]) # sqlRead the first chain aloud as "the company's teams, the first one, its members, the second one, its skills, the first one." If a chain is hard to say this way, it is probably worth splitting.
Know the type at each level
Each step needs the right kind of index for the container in front of it. The table lists the usual containers and what goes wrong with a bad lookup.
| Container | What you put in `[...]` | Typical failure |
|---|---|---|
| list | an integer, negative integer, or slice | `IndexError` if out of range, `TypeError` if you use a string |
| dict | any hashable key that exists | `KeyError` if the key is absent |
| tuple | an integer or slice | `IndexError` if out of range |
| string | an integer or slice | `IndexError` if out of range |
| int, float, `None`, `bool` | nothing, these are not subscriptable | `TypeError` |
Strings are subscriptable, which surprises people. students[0]["name"][0] is valid and returns "A", because the string "Ana" is indexed like a sequence. A chain that goes one level too deep into a string does not always fail. It can silently return a single character instead of raising an error.
Negative indexes and slices in a chain
Negative indexes count from the end of a list, so -1 is the last element. They work at any level of a chain:
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
print(students[-1]["name"]) # Ben
print(students[1]["grades"][-1]) # 92
print(students[1]["grades"][:2]) # [70, 88]
print(students[1]["grades"][:2][0]) # 70A slice returns a new list, so you can keep chaining after it. The slice is only a shallow copy, though. It holds the same inner objects as the original list:
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
top = students[:1]
print(top is students) # False
print(top[0] is students[0]) # TrueThe new outer list is separate, but the dictionary inside it is the very same object. This matters once you start changing data, and a later chapter on shared references returns to it. For now, remember that reading never copies anything. Any lookup hands you the original inner object.
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
grades = students[1]["grades"]
print(grades is students[1]["grades"]) # TrueName the in-between values
Long chains repeat work and are hard to read. When you need several values from the same inner object, store that object once:
company = {
"name": "Acme",
"teams": [
{
"name": "Core",
"members": [
{"name": "Ana", "skills": ["python", "sql"]},
{"name": "Ben", "skills": ["go"]},
],
},
],
}
# Repetitive
print(company["teams"][0]["members"][0]["name"])
print(company["teams"][0]["members"][0]["skills"])
# Clearer
ana = company["teams"][0]["members"][0]
print(ana["name"]) # Ana
print(ana["skills"]) # ['python', 'sql']Because ana refers to the same dictionary as the one inside company, it is a cheap alias and not a copy. This is a good habit for two reasons. The code reads better, and a lookup that fails will point at a short line.
Common errors and what they tell you
Most errors in nested reads come from a mismatch between what you think a level holds and what it actually holds. The exception type tells you which kind of mismatch it is. The next script triggers five of them on purpose:
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
def attempt(label, func):
try:
func()
except (KeyError, IndexError, TypeError) as err:
print(f"{label}: {type(err).__name__}: {err}")
attempt("string index on a list", lambda: students["Ana"])
attempt("integer key on a dict", lambda: students[0][1])
attempt("index past the end", lambda: students[5])
attempt("one level too deep", lambda: students[0]["grades"][0][0])
attempt("missing key", lambda: students[0]["email"]["domain"])Running it prints:
string index on a list: TypeError: list indices must be integers or slices, not str
integer key on a dict: KeyError: 1
index past the end: IndexError: list index out of range
one level too deep: TypeError: 'int' object is not subscriptable
missing key: KeyError: 'email'Here is how to read each message:
TypeError: list indices must be integers or slices, not str. You used a dictionary-style key on a list. The outer container is a list, so you probably forgot to pick an element first.KeyError: 1. You used a list-style index on a dictionary. The dictionary has no key1, so the level above it is a dict where you expected a list.IndexError: list index out of range. The list is shorter than you assumed. Remember that a list of lengthnhas valid indexes0ton - 1.TypeError: 'int' object is not subscriptable. The chain went deeper than the data. The message names the type that you tried to index, which tells you where the data ends.KeyError: 'email'. The dictionary exists but has no such key. The key in the message is the one that failed, not the whole path.
A related message is 'NoneType' object is not subscriptable. It means a previous step returned None, often because a function or a dict.get() call found nothing. The chain continued from None and failed on the next subscript.
Locating the failing level
When a long chain fails, split it and print the pieces. Check the type and content of each level in turn:
company = {"teams": [{"name": "Core", "members": []}]}
team = company["teams"][0]
print(type(team).__name__, team) # dict {'name': 'Core', 'members': []}
members = team["members"]
print(type(members).__name__, members) # list []
print(len(members)) # 0The empty list explains why company["teams"][0]["members"][0] would raise IndexError. The keys were all correct, but the list had no elements. This step-by-step check is slower than reading the traceback, but it always works. Recent Python versions mark the failing part of a line in the traceback, which also helps, but the marker can be less precise on lines that contain several subscripts.
Two cheap checks help while you explore unfamiliar data:
type(value)shows what kind of container you are holding.len(value)shows whether an index is possible, andlist(value)on a dictionary shows its keys.
record = {"id": 7, "tags": ["a", "b"], "owner": {"name": "Ana"}}
print(list(record)) # ['id', 'tags', 'owner']
print(type(record["tags"])) # <class 'list'>
print(list(record["owner"])) # ['name']Dictionary keys can be more than strings
Dictionary keys must be hashable, but they do not have to be strings. Integers and tuples are common, and each level of a chain uses whatever key type that dictionary was built with:
scores = {
2024: {"ana": [90, 85]},
2025: {"ana": [92], "ben": [70, 88]},
}
print(scores[2025]["ben"][1]) # 88
grid = {(0, 0): "start", (0, 1): "path"}
print(grid[(0, 1)]) # pathBe careful here. scores[2025] uses the integer 2025, and scores["2025"] raises KeyError because the string is a different key. When JSON data is loaded later in this tutorial, you will see this mismatch again, because JSON object keys are always strings.
Summary of the model
A chain is a sequence of single lookups, each applied to the result of the one before. Every level needs an index that suits its type. Reading returns the original inner object and does not copy it. When a chain fails, the exception type tells you whether the type, the key, or the length was wrong. The next chapter builds on this by changing values at the end of a chain.
Exercise
Given data = {"teams": [{"name": "A", "scores": [3, 5]}, {"name": "B", "scores": [4, 9, 6]}]}, write one expression that returns the last score of team B without using the number 2 or the number 3. Then say which exception data["teams"]["B"] raises and why.
Show answer
Use data["teams"][1]["scores"][-1], which returns 6. The negative index -1 picks the last element regardless of length. The expression data["teams"]["B"] raises TypeError: list indices must be integers or slices, not str, because data["teams"] is a list and a list cannot be indexed with a string. The team has to be chosen by position first, or found by searching.
Exercise
The chain config["servers"][0]["ports"][0][1] raises TypeError: 'int' object is not subscriptable. What does this tell you about the data, and how would you find out how deep it really goes?
Show answer
The value at config["servers"][0]["ports"][0] is an integer, so the final [1] tried to index a number. The ports list holds plain integers and not lists. To check, assign each level to a variable and print type() and the value, for example ports = config["servers"][0]["ports"] followed by print(ports) and print(type(ports[0])). Then remove the last subscript from the chain.