Nested Structures
Unit ID: M03-U06 Estimated active time: 25-35 minutes
Records often live inside sequences
Consider a small fictional dataset:
courses = [
{"code": "AI-01", "title": "AI Foundations", "hours": 8},
{"code": "PY-01", "title": "Python Foundations", "hours": 32},
]
The outer object is a list. Each list item is a dictionary. The access path must follow that shape.
Read one field step by step
first_course = courses[0]
first_title = first_course["title"]
print(first_title)
You can write the path directly:
print(courses[0]["title"])
The step-by-step version is easier to inspect while learning or debugging.
Add a nested collection
courses[0]["tags"] = ["ai", "beginner"]
print(courses[0]["tags"][1])
The access path means:
- take list item
0; - read its
"tags"field; - take tag item
1.
Draw the shape before guessing
Use indentation to make nesting visible:
courses: list
item 0: dictionary
code: string
title: string
hours: integer
tags: list
item 0: string
item 1: string
When an access fails, check each step's type.
Common path errors
courses["title"]
This fails because courses is a list, not a dictionary.
courses[0][0]
This fails because the first record is a dictionary whose meaningful access uses keys.
courses[3]["title"]
This fails because the list has only two items.
Preserve the source before editing
To experiment with the second record:
working_course = courses[1].copy()
working_course["hours"] = 30
The original second dictionary remains unchanged because the edited fields are scalar values. If a nested list is edited, copy that nested list too.
Practice
Add a third fictional course dictionary. Then retrieve its code, add a two-item tag list, and retrieve the final tag. Explain each access step and its type.
Takeaway
Nested access follows the data shape one level at a time. Separate steps while debugging, inspect each type, and copy the level you intend to change. Next, we will summarise and convert collections using readable built-in operations.
