1 of 26

Section 6

Nested Structures

QOTD: What song would you pick as the soundtrack to your life?

CSE 160

CSE 160: Nested Structure

2 of 26

Logistics

  • Written check-in #6 due Fri July 31
  • Programming practice #5 due Sun. Aug 2
  • HW4 due Mon Aug 3
    • Submitting on Gradescope
    • Wait for autograder!

CSE 160: Nested Structure

3 of 26

Lecture Review: Nested Structures

CSE 160: Nested Structure

4 of 26

Review of nested structures

  • So far you have seen lists and dictionaries.
  • There are ways to combine them into nested structures in order to represent different types of data.

Nested Structure

Example

List of lists

Pixel grids

Dictionaries with lists as values

centroids_dict

List of dictionaries

Excel data with column headers

Dictionary of dictionaries

Excel data with row and column headers

CSE 160: Nested Structure

5 of 26

Review of nested structures

  • Why do we care about nested structures?
    • A lot of the data that we work with in real life come in tables, which cannot be represented by a single list or dictionary

CSE 160: Nested Structure

6 of 26

Nested Lists

  • Useful for representing data in which only the order matters.
  • Can be multidimensional.
  • Used in HW 3 for image data (how would you represent color images?)

255

0

255

0

0

255

255

255

255

CSE 160: Nested Structure

7 of 26

Dictionary with Lists as Values

  • In homework 4, these will be used to hold centroids and the points associated with them.
  • Can also be used to represent multiple observations for each data point.
    • Example: Race times were measured three times for three different people

{"p1": [10.0, 10.5, 9.9], "p2": [8.0, 9.5, 9.2], "p3": [8.0, 8.2, 10.1]}

CSE 160: Nested Structure

8 of 26

Lists of Dictionaries

  • List of dictionaries:
    • [{‘a’ : 1, ‘b’ : 2, ‘c’ : 3}, {‘a’ : 4, ‘b’ : 5, ‘c’ : 6}, {‘d’ : 1, ‘e’ : 2, ‘f’ : 3}]
  • They might be used to represent a table (e.g. an excel file)
    • Where each item in the list in the dictionary is a row in the table
    • In this version, each dictionary should have the same keys 
  • Example:
    • [{‘County’ : ‘King’, ‘Population’ : 2269675, "Temperature" : 57}, {‘County’ : ‘Pierce’, ‘Population’ : 921130, "Temperature" : 61}, {‘County’ : ‘Snohomish’, ‘Population’ : 827957, "Temperature" : 53}]

CSE 160: Nested Structure

9 of 26

Nested Dictionaries

  • Dictionaries themselves can hold mutable elements as values which means we can put a dictionary inside a dictionary

    • {"dict_1" : {"a" : 1, "b" : 2, "c" : 3}, "dict_2" : {"a" : 5, "b" : 4, "c" : 3}, "dict_3" : {"a" : 1, "b" : 2, "c" : 3}}
    • Can have duplicate values

  • This can be used to better categorize data, transforming the list of dictionaries

    • {‘King’ : {‘Population’ : 2269675, ‘Temperature’ : 57}, ‘Pierce’ : {‘Population’ : 921130 , ‘Temperature’ : 61}, ‘Snohomish’ : {‘Population’ : 827957 , "Temperature" : 53}}

    • Can now easily find information based on county instead of traversing through a list

CSE 160: Nested Structure

10 of 26

How would we represent this data in python?

CSE 160: Nested Structure

11 of 26

Section Handout Problems

CSE 160: Nested Structure

12 of 26

Problem 1

1. Write a function called sum_lists(dict_list) that when given a dictionary with lists as values returns a list that is the sum of all the lists for each index. Assume that all of the lists are of the same length.

Hint: You can find the length of the list by using len(dict_list["list_1"]).

Example:.

{"list_1" : [5, 10, 90],

"list_2" : [45, 78, 0],

"list_3" : [90, 0, 10]}

Should return:

[140, 88, 100] => Because 5 + 45 + 90 = 140 and so on

CSE 160: Nested Structure

13 of 26

Problem Breakdown

  • Identify Problem & create function

  • The function starts by creating an empty list to store the final summed values

  • The outer loop runs once for each index in the lists, using the length of "list_1"

  • A total variable is reset to zero at the start of each index iteration

  • The inner loop goes through every list stored in the dictionary’s values

  • Each list adds its value at the current index to total

  • After summing all lists for that index, the result is appended to output_list and returned at the end!

CSE 160: Nested Structure

14 of 26

Problem 1

def sum_lists(dict_list):

output_list = []

for i in range(len(dict_list["list_1"])):

total = 0

for list in dict_list.values():

total += list[i]

output_list.append(total)

return output_list

CSE 160: Nested Structure

15 of 26

Problem 2

Write a function called sum_dict(nested_dict) that, given a dictionary of dictionaries, creates a single dictionary containing the sums of values with the same key in the given dictionaries.

For example: Given this dictionary of dictionaries:

{"dict_1" : {"b": 10, "a": 5, "c": 90},

"dict_2" : {"b": 78, "a": 45},

"dict_3" : {"a": 90, "c": 10}}

Your code should create : {"b": 88, "a": 140, "c": 100}

CSE 160: Nested Structure

16 of 26

Problem 2

def sum_dict(nested_dict):

new_dict = {}

for inner_dict in nested_dict.values():

for key in inner_dict:

if key not in new_dict:

new_dict[key] = 0

new_dict[key] += inner_dict[key]

return new_dict

CSE 160: Nested Structure

17 of 26

Problem 3

Write a function called reformat_dict(dict_list, new_key) that when given a list of dictionaries and a key returns a dictionary of dictionaries with the keys being the value of the given key for each dictionary and the value being a dictionary with the rest of the information.

For example, given: key = "County"

dict_list = [{"County": "King", "Population": 2269675, "Temperature": 57},{"County": "Pierce", "Population": 921130, "Temperature": 61},{"County": "Snohomish", "Population": 827957, "Temperature": 53}]

Your code should produce:

{‘King’ : {‘Population’ : 2269675, ‘Temperature’ : 57}, ‘Pierce’ : {‘Population’ : 921130 , ‘Temperature’ : 61}, ‘Snohomish’ : {‘Population’ : 827957 , "Temperature" : 53}}

CSE 160: Nested Structure

18 of 26

Problem 3

def reformat_dict(dict_list, new_key):

new_dict = {}

for inner_dict in dict_list:

current_key = inner_dict[new_key]

new_dict[current_key] = {}

for key in inner_dict:

if key != new_key:

new_dict[current_key][key] = inner_dict[key]

return new_dict

CSE 160: Nested Structure

19 of 26

Additional Problems

CSE 160: Nested Structure

20 of 26

Problem 4

Given a file.txt that looks like the following, write a function called read_data(file_name) that reads the data and outputs a list of dictionaries, where the first row of file_name contains the keys and the subsequent rows of file_name are the values of each dictionary. You may assume that the format will exactly follow the example below, with spaces in between each word/number.

example.txt:

state city zip

Washington Seattle 733919

Oregon Portland 641162

California San-Francisco 815201

Michigan Detroit 632464

Example Output:

[{"state": "Washington", "city": "Seattle", "zip": "733919"},

{"state": "Oregon", "city": "Portland", "zip": "641162"},

{"state": "California", "city": "San-Francisco", "zip": "815201"},

{"state": "Michigan", "city": "Detroit", "zip": "632464"}]

CSE 160: Nested Structure

21 of 26

Problem 4

def read_data(file_name):

nested_dict = {}

file = open(example.txt)

for line in file:

data = line.split()

inner_dict = {}

inner_dict[data[1]] = data[2]

nested_dict[data[0]] = inner_dict

file.close()

return nested_dict

CSE 160: Nested Structure

22 of 26

Example 2: Structured Strings

22

Instead of analyzing DNA (A, T, C, G) sequences like in HW2, now you are given an RNA (A, U, C, G) sequence as an input string. Each sequence of three nucleotides could translate to an amino acid.

"AUG" - "Methionine"

"UGC" - "Crysteine"

"UCU" - "Serine"

Use a for loop, range, and string slicing to "translate" an RNA sequence to amino acids.

Your Task

"AUGCUCAUG"

["Methionine", "Methionine"]

"ACCUUUAUGAUUUGCUCUUUUUGCUCU"

["Methionine", "Crysteine", "Serine", "Crysteine", "Serine"]

CSE 160: Nested Structres

23 of 26

Example 2: Structured Strings

23

Instead of analyzing DNA (A, T, C, G) sequences like in HW2, now you are given an RNA (A, U, C, G) sequence as an input string. Each sequence of three nucleotides could translate to an amino acid.

Use a for loop, range, and string slicing to "translate" an RNA sequence to amino acids.

Your Task

"AUGCUCAUG"

["Methionine", "Methionine"]

"ACCUUUAUGAUUUGCUCUUUUUGCUCU"

["Methionine", "Crysteine", "Serine", "Crysteine", "Serine"]

1. Understand Inputs → Outputs

TAKEAWAY: Move in steps of 3

"AUG" - "Methionine"

"UGC" - "Crysteine"

"UCU" - "Serine"

CSE 160: Nested Structres

24 of 26

Example 2: Structured Strings (Subproblem 1)

24

Instead of analyzing DNA (A, T, C, G) sequences like in HW2, now you are given an RNA (A, U, C, G) sequence as an input string. Each sequence of three nucleotides could translate to an amino acid.

"AUG" - "Methionine"

"UGC" - "Crysteine"

"UCU" - "Serine"

"AUGCUCAUG"

["Methionine", "Methionine"]

2. Subproblem 1:

RNA sequence to amino acid

Use a for loop, range, and string slicing to "translate" an RNA sequence to amino acids.

Your Task

CSE 160: Nested Structres

25 of 26

Example 2: Structured Strings (Subproblem 2)

25

Instead of analyzing DNA (A, T, C, G) sequences like in HW2, now you are given an RNA (A, U, C, G) sequence as an input string. Each sequence of three nucleotides could translate to an amino acid.

"AUG" - "Methionine"

"UGC" - "Crysteine"

"UCU" - "Serine"

"AUGCUCAUG"

["Methionine", "Methionine"]

2. Subproblem 1:

RNA sequence to amino acid

Use a for loop, range, and string slicing to "translate" an RNA sequence to amino acids.

Your Task

3. Subproblem 2:

Iterate over RNA in steps of 3

TAKEAWAY: Move in steps of 3

CSE 160: Nested Structres

26 of 26

Written Check In #6 Due Tomorrow

CSE 160: Nested Structure