1 of 10

Nested Structures Practice

Winter 2025

1

Adrian Salguero

2 of 10

Announcements

  • Homework 4, Part 1 due Monday at 11:59pm
  • Coding Practice 5 due Wednesday at 11:59pm
  • Midterm this Wednesday (February 12th) in class
    • Reference sheet will be provided
    • 1 page of notes (front and back, handwritten or typed) - will be collected
    • DRS accommodations → register with the DRS Testing Center
    • Exam will cover all material up to today (no sets or tuples)

2

3 of 10

Nested Structures in Python

  • Nested Lists
  • Nested Dictionaries
  • Dictionaries with Lists as Values
    • Lists that are values can be updated
    • Elements can be added/removed without having to remove the lists from the dictionary
  • Dictionaries with Tuples as Keys/Values
    • Not covered in this lecture but know it is a thing

3

4 of 10

Practice Problem 1: Nested Lists

Suppose you are given the nested list below called matrix. Write code that creates a new list that keeps track of the products of each row of the matrix.

Example

[ [1, 1, 1],

[2, 2, 2],

[3, 3, 3] ]

4

Output

[1, 8, 27]

5 of 10

Problem 1 Solution

matrix = [ [1, 1, 1],

[2, 2, 2],

[3, 3, 3] ]

products = []

for r in range(len(matrix)):

p = 1

for c in range(len(matrix[r])):

p*=matrix[r][c]

products.append(p)

print(products)

5

6 of 10

Practice Problem 2: Nested Dictionaries

Given a file.txt (as seen below), write a function called read_data(file_name) that reads the data and returns a nested dictionary where the first entry is the outer key, the second key is the inner key, and the third entry is the value of the inner dictionary.

File.txt

Washington Seattle 733919

Oregon Portland 641162

California San Francisco 815201

Michigan Detroit 632464

6

Expected Output

{“Washington”: {“Seattle”: 733919},

“Oregon”: {“Portland”: 641162},

“California”: {“San Francisco”: 815201},

“Michigan”: {“Detroit”: 632464}}

7 of 10

Problem 2 Solution

def read_data(filename):

myfile = open(filename, "r")

d = {}

for line in myfile:

words = line.strip().split()

state = words[0]

number = words[len(words) - 1] #words[-1]

city_list = words[1:len(words)-1]

city = ""

for word in city_list:

city = city + word + " "

city = city.strip() # Remove trailing whitespace

d[state] = {}

d[state][city] = number

myfile.close()

return d

print(read_data("file.txt"))

7

8 of 10

Practice Problem 3: Dictionaries with Lists

Given a file donations.txt, as seen below. Notice the first word in each line represents the type of organization and the second word is the name of the organization itself. Write code that reads in the file and creates a dictionary where the keys are the type of organization and the value is a list of all organizations falling under that category.

donations.txt

environment WRI

environment Sierra Club

education Khan Academy

poverty Oxfam

poverty Care International

disaster Red Cross

8

Expected Output

{“environment: [“WRI”, “Sierra Club”],

“education”: [“Khan Academy”],

“poverty”: [“Oxfam”, “Care International”],

“disaster”: [“Red Cross”] }

9 of 10

Problem 3 Solution

myfile = open("donations.txt")

d = {}

for line in myfile:

words = line.strip().split()

category = words[0]

organization = words[1:]

organization_name = ""

for i in organization:

organization_name = organization_name + i + " "

organization_name = organization_name.strip()

# Check if the category exists in the dictionary

# If it exists, add to the list

# If its a new category, create list with the current organization as the only element

if category in d:

d[category].append(organization_name)

else:

d[category] = [organization_name]

print(d)

myfile.close()

9

10 of 10

When to use a list? When to use a dictionary?

  • Lists
    • You want to store a collection of items
    • You want to maintain some level of order
    • You want to iterate through (loop through) the data at some point
  • Dictionaries
    • You want to map one value (a key) to another (the value)
    • Quick retrieval of information
    • Store data with a unique identifier or label (the label can be the key)

10