Nested Structures Practice
Winter 2025
1
Adrian Salguero
Announcements
2
Nested Structures in Python
3
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]
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
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}}
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
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”] }
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
When to use a list? When to use a dictionary?
10