Nesting and Choosing the Right Structure
Real data is often a structure inside a structure. The most common shape is a list of dicts, like rows in a table where each row is a record:
people = [
{"name": "Ada", "age": 36},
{"name": "Sam", "age": 29},
]
print(people[0]["name"]) # Ada
print(people[1]["age"]) # 29You reach in step by step: people[0] is the first dict, then ["name"] pulls its name. Loop over the records like this:
for p in people:
print(p["name"], p["age"])How do you choose which structure to use? A quick guide:
- list when order matters and items can repeat (a queue, a log)
- tuple when the group is fixed and should not change (a coordinate)
- dict when you look things up by a name or id (a record, a config)
- set when you only care about unique membership (tags, seen ids)
You can mix them freely: a dict whose values are lists, a list of tuples, and so on.
Given the list of dicts people in the starter, write a loop that adds up every person's "age" into a variable total_age. Then store the name of the first person in first_name.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.