Skip to content

Nov 08: 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

PA2-B Debrief

  • Tests:
    • test_election_b.py
    • test_vote_file_processor_b.py
  • Code:
    • election_b.py
    • vote_file_processor_b.py

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")

Question 13

for i in range(6):
    for j in range(7):
        print(i, '+', j, '=', i + j)

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"],
    },
}