Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 3 · Working with Nested Data Structures

Working with Nested Data Structures

On this pageList of Dictionaries — A Collection of RecordsDictionary of Lists — Grouping Related ValuesDictionary of Dictionaries — Nested InformationTuples Inside Collections — Storing Fixed InformationAccessing and Updating Nested DataMini Project — City Weather Tracker

Combining lists, tuples, and dictionaries for structured data

Real-world data is rarely flat. A class has many students; each student has several courses; each course has a grade. To model this cleanly, we nest Python’s core collections: lists, tuples, and dictionaries. Nesting combines familiar collections into structured records. We will later use JSON to exchange such records with other programs.

List of Dictionaries — A Collection of Records

A list of dictionaries is often used when you have several similar items, each described by key–value pairs. This is common when storing records like users, books, or products.

books = [
    {"title": "To Kill a Mockingbird", "author": "Harper Lee", "year": 1960},
    {"title": "1984", "author": "George Orwell", "year": 1949},
    {"title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "year": 1925}
]

print(books[0]["title"])  # Access the first book's title
print(books[1]["author"]) # Access the second book's author
Listing 185 — List of Dictionaries — A Collection of Records

Output

To Kill a Mockingbird
George Orwell

This format is flexible — you can easily add, remove, or filter items, making it useful for things like contact lists, library catalogs, or e-commerce products.

Sometimes, you need to group multiple items under one category. For example, imagine a grocery store that keeps track of products available in each section.

store_sections = {
    "Fruits": ["Apples", "Bananas", "Mangoes"],
    "Vegetables": ["Carrots", "Broccoli", "Spinach"],
    "Bakery": ["Bread", "Croissant"]
}

# Add a new item
store_sections["Bakery"].append("Muffins")
print(store_sections["Bakery"])
Listing 186 — Dictionary of Lists — Grouping Related Values

Output

['Bread', 'Croissant', 'Muffins']

This structure is perfect when one key naturally points to a group of related items — like playlists in a music app or classes offered in a department.

Dictionary of Dictionaries — Nested Information

You can also create a dictionary where each value is another dictionary. This allows for more detailed data — like customer information in an online store.

customers = {
    "C001": {"name": "Alice", "email": "alice@example.com", "points": 1200},
    "C002": {"name": "Bob", "email": "bob@example.com", "points": 800},
}

print(customers["C001"]["name"])  # Access Alice’s name
customers["C002"]["points"] += 200  # Update Bob’s points
print(customers["C002"])
Listing 187 — Dictionary of Dictionaries — Nested Information

Output

Alice
{'name': 'Bob', 'email': 'bob@example.com', 'points': 1000}

This kind of structure is widely used in school systems where each student has multiple courses, and each course stores a grade, as well as in business databases where each customer may have multiple orders, and each order contains several products with their details.

Tuples Inside Collections — Storing Fixed Information

Tuples are useful when you want to store fixed, ordered data that should not change — such as coordinates, prices, or dimensions.

cities = {
    "Paris": (48.8566, 2.3522),
    "London": (51.5074, -0.1278),
    "Tokyo": (35.6895, 139.6917)
}

lat, lon = cities["Tokyo"]
print(f"Tokyo is located at {lat}°N, {lon}°E")
Listing 188 — Tuples Inside Collections — Storing Fixed Information

Output

Tokyo is located at 35.6895°N, 139.6917°E

Tuples provide structure and stability to small data elements that belong together and should remain unchanged.

Accessing and Updating Nested Data

To access or update nested data, you simply chain together the right indices or keys. For example, consider a school record where students are stored by name, and each student has grades for multiple subjects:

students = {
    "Alice": {"Math": 88, "English": 92},
    "Bob": {"Math": 75, "English": 85}
}

# Access data
print(students["Alice"]["English"])  # 92

# Update data
students["Bob"]["Math"] = 80
print(students["Bob"])
Listing 189 — Accessing and Updating Nested Data

Output

92
{'Math': 80, 'English': 85}

Nested structures make it easy to represent detailed, real-world relationships — like a person with multiple addresses, or a restaurant with menus by category.

Mini Project — City Weather Tracker

Write a program that tracks average temperatures for several cities. Each city will have monthly data stored in a nested dictionary. The user can add new temperature data and view city summaries.

Tasks:

  • Create a dictionary where each key is a city name and each value is another dictionary of months and average temperatures.
  • Start with Paris: January 5°C and July 25°C; London: January 6°C and July 20°C.
  • Add a city, update a month, display the records, and calculate the mean of the months recorded for each city. A mean of a few selected months is not an annual mean.
  • Build the interactive version after For Loops and Built-in Functions. Until then, practise direct updates to these nested records.

Example Run:

Enter a city name: Paris
Enter the month: March
Enter the average temperature: 12

Updated weather data for Paris: {'January': 5, 'July': 25, 'March': 12}

Mean of recorded monthly temperatures:
Paris: 14.0°C
London: 13.0°C
Listing 190 — Mini Project — City Weather Tracker