Skip to Content
Course content

43: Nested Data Structures

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think about a physical filing cabinet in an old office. You don't just throw every piece of paper into one giant pile; that would be a nightmare to manage. Instead, you have the cabinet itself, which contains several drawers. Inside each drawer, you have hanging folders. Inside those folders, you might have individual sheets of paper or even smaller envelopes containing receipts.

This is exactly how nested data structures work in Python. You aren't just using a list or a dictionary; you're putting one inside the other to create a hierarchy. To map this to code: the cabinet is your outer list, the drawers are lists within that list, the folders are dictionaries, and the receipts are the actual strings or integers you're storing.

Thinking in Layers

When I'm designing a piece of software, I usually start by sketching out the "shape" of the data. Let's say we're building a simple system to track a player's inventory in an RPG. A single list of items isn't enough because players have different bags, and each item has multiple properties like weight and value.

# A list (the cabinet) containing dictionaries (the folders)
# and those dictionaries containing lists (the receipts)
player_inventory = [
    {
        "bag_name": "Main Backpack",
        "capacity": 20,
        "items": ["Healing Potion", "Iron Sword", "Wooden Shield"]
    },
    {
        "bag_name": "Small Pouch",
        "capacity": 5,
        "items": ["Gold Coin", "Mysterious Key"]
    }
]

Look at what happened here. We have a list, but its elements aren't just strings—they are dictionaries. And inside those dictionaries, the value for the key "items" is another list. This is where most beginners get a bit dizzy, but the trick is to stop looking at the whole thing and just look at one layer at a time.

Drilling Down to the Data

To get to a specific piece of information, you just have to "follow the path." I like to think of it as a set of directions. If I want to find the "Mysterious Key," I have to tell Python exactly how to get there.

# 1. Which bag? The second one (index 1)
# 2. Which property of that bag? The "items" list
# 3. Which item in that list? The second one (index 1)

key = player_inventory[1]["items"][1]
print(f"Found it: {key}") # Output: Found it: Mysterious Key

If you try to jump the gun and call player_inventory["items"], Python will throw a TypeError. Why? Because player_inventory is a list, and lists only understand numbers (indices), not string keys. You have to enter the list first, then you can use the dictionary keys.

Changing the Inside Without Breaking the Outside

Updating nested data is similar to accessing it. You drill down to the exact spot you want to change and then use the assignment operator. I've seen a lot of people accidentally overwrite an entire dictionary when they only meant to change one value inside it—be careful with that.

# Let's say the player finds a "Magic Map" and puts it in their Main Backpack
player_inventory[0]["items"].append("Magic Map")

# Or, let's upgrade the capacity of the Small Pouch
player_inventory[1]["capacity"] = 10

Notice that we didn't have to redefine the whole player_inventory variable. We just pointed to the specific "drawer" and "folder" we wanted to modify. It's efficient, and it keeps your data organized as your project grows from a tiny script into a full-blown application.




📋 Practical Task

The Galactic Trading Post Inventory Manager

You are managing a space station's warehouse. Your data is stored as a list of "Hangers," where each hanger is a dictionary. Each dictionary contains the hanger's name and a dictionary of "Cargo" (where the key is the item name and the value is the quantity).

Your task:

  1. Create the following structure:
    • Hanger A: Cargo contains {"Fuel Cells": 50, "Oxygen Tanks": 20}
    • Hanger B: Cargo contains {"Titanium Plates": 100, "Plasma Coils": 10}
  2. The station just received a shipment of 30 more "Oxygen Tanks" for Hanger A. Update the quantity in the nested structure.
  3. A trader bought 5 "Plasma Coils" from Hanger B. Update that quantity.
  4. Print a sentence that says: "Hanger A now has [X] Oxygen Tanks," where [X] is the updated value retrieved from your nested structure.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.