Skip to content

Nov 10: Nested Data Structures

Learning Objectives

After today's class, you should be able to:

  • Explain how rows and columns of data can be stored in lists.
  • Write nested for loops to iterate data and compute functions.
  • Represent complex data using nested dictionaries and lists.

Reminders

POGIL Activity

  • Nested Structures
    • If you are absent today, complete this activity at home
    • Bring your completed activity to class or office hours
  • Python Tutor – to visualize the examples below

Model 1: Nested Lists

grid = [
    [' ', ' ', ' ', ' ', ' ', ' ', ' '],
    [' ', ' ', ' ', ' ', ' ', ' ', ' '],
    ['Y', ' ', ' ', ' ', 'Y', 'Y', ' '],
    ['R', ' ', ' ', 'Y', 'R', 'R', ' '],
    ['R', 'R', 'Y', 'R', 'Y', 'R', ' '],
    ['R', 'Y', 'R', 'Y', 'Y', 'Y', 'R'],
]

Model 2: Nested Loops

groceries = ["Apples", "Milk", "Flour", "Chips"]
for item in groceries:
    print("Don't forget the", item)

count = 0
for row in grid:  # outer loop
    print("row =", row)
    for cell in row:  # inner loop
        print("cell =", cell)
        if cell == ' ':
            count += 1
print(count, "spaces remaining")

Model 3: Nested Objects

movies = {
    "Casablanca": {
        "year": 1942,
        "genres": ["Drama", "Romance", "War"],
    },
    "Star Wars": {
        "year": 1977,
        "genres": ["Action", "Adventure", "Fantasy"],
    },
    "Groundhog Day": {
        "year": 1993,
        "genres": ["Comedy", "Fantasy", "Romance"],
    },
}