Syllabus Lesson 34 of 239 · Data Structures
Data Structures

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"])    # 29

You 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.

Your turn

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.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output