CSE 160 Section 8
Dictionaries, Nested Structures, and Tuples
CSE 160: Section 8
Logistics
CSE 160: Section 8
Lecture Recap
CSE 160: Section 8
Dictionary
heights = {"Ella": 68,
"Martin": 72,
"Lilly": 49,
"William": 50,
"Simon": 70}
print(heights["Lilly"]) # 49
print(heights["Wen"]) # KeyError
heights["Wen"] = 63 # Add a key-value pair
heights["Lilly"] = 50 # Update value
print(heights["Lilly"]) # 50
# print out all keys
for key in heights.keys():
print(key)
# print out all values
for value in heights.values():
print(value)
# print out keys and values
for (key, value) in heights.items():
print(key, value)
# another method
for key in heights:
value = heights[key]
print(key, value)
CSE 160: Section 8
Dictionary built-in functions
Operation (dictionary d) | Description |
d.items() | Returns a list containing a tuple for each key-value pair. |
d.keys() | Returns a list of the dictionary keys. |
d.values() | Returns a list of all values in the dictionary. |
CSE 160: Section 8
Tuples
Description | Example | list | tuple |
indexing | name[i] | ✅ | ✅ |
negative indexing | name[-i] | ✅ | ✅ |
slicing | name[i:j] | ✅ | ✅ |
checking if item exists | item in name | ✅ | ✅ |
looping | for item in name | ✅ | ✅ |
length | len(name) | ✅ | ✅ |
changing items | name[i] = item | ✅ | 🚫 |
appending items | name.append(item) | ✅ | 🚫 |
use as dict keys | dict(name:val) | 🚫 | ✅ |
CSE 160: Section 8
A tuple is an immutable sequence
7
# Creating tuples
w = (4, 7, 9)
x = ("once", "upon", "a", "time")
y = () # An empty tuple
z = "rea2000", "blue" # parenthesis can make things � # clearer but are often not needed
CSE 160: Section 8
Section Handout Problems
CSE 160: Section 8
Warm-Up Problem
What does the following code print?
cost = {"electricity": 90, "water": 60}
cost["electricity"] += 25
cost["internet"] = 100
for utility in cost:
if cost[utility] > 100:
print(utility, cost[utility])
CSE 160: Section 8
Warm-Up Problem (Solution)
What does the following code print?
cost = {"electricity": 90, "water": 60}
cost["electricity"] += 25
cost["internet"] = 100
for utility in cost:
if cost[utility] > 100:
print(utility, cost[utility])
electricity 115
CSE 160: Section 8
Problem 3
Part A. Write pokemon_types (pokemon_dict) that takes parameter pokemon_dict and returns a new dictionary mapping each type of pokemon to the number pokemon in pokemon_dict with that type.
Ex: when pokemon_dict = {"pikachu": "electric", "charmander": "fire", "charizard": "fire"}
then…. pokemon_types(pokemon_dict) returns {"electric" : 1, "fire":2}
CSE 160: Section 8
Problem 3 (Solution)
Part A. Write pokemon_types (pokemon_dict) that takes parameter pokemon_dict and returns a new dictionary mapping each type of pokemon to the number pokemon in pokemon_dict with that type.
Ex: when pokemon_dict = {"pikachu": "electric", "charmander": "fire", "charizard": "fire"}
then…. pokemon_types(pokemon_dict) returns {"electric" : 1, "fire":2}
def pokemon_types(pokemon_dict):
type_counts = {}
for pokemon in pokemon_dict:
pokemon_type = pokemon_dict[pokemon]
if pokemon_type in type_counts:
type_counts[pokemon_type] += 1
else:
type_counts[pokemon_type] = 1
return type_counts
CSE 160: Section 8
Problem 3
Part B. Returns a new dictionary mapping each type of pokemon to the list of pokemon with that type.
For example, when pokemon_dict=
{"pikachu":"electric","charmander":"fire","charizard": "fire"}
Then…. pokemon_types(pokemon_dict) returns {'electric': ['pikachu'], 'fire': ['charmander', 'charizard']}
CSE 160: Section 8
Problem 3 (Solution)
Part B. Returns a new dictionary mapping each type of pokemon to the list of pokemon with that type.
For example, when pokemon_dict=
{"pikachu":"electric","charmander":"fire","charizard": "fire"}
Then…. pokemon_types(pokemon_dict) returns {'electric': ['pikachu'], 'fire': ['charmander', 'charizard'}
def pokemon_types(pokemon_dict):
type_groups = {}
for pokemon in pokemon_dict:
pokemon_type = pokemon_dict[pokemon]
if pokemon_type in type_groups:
type_groups[pokemon_type].append(pokemon)
else:
type_groups[pokemon_type] = [pokemon]
return type_groups
CSE 160: Section 8
Problem 5
A marathon race has recorded the finishing results of several runners. Each runner's information is stored in a tuple in the format: (runner_name, country, finish_time_minutes)
You must use indexing.
Given:
results = (
("Daniel", "USA", 125),
("Kenji", "Japan", 118),
("Maria", "Spain", 130),
("Lina", "Kenya", 115),
("Arjun", "India", 140)
)
Part A. Print each runner’s name and finish time
CSE 160: Section 8
Problem 5 (Solution)
Part A. Print each runner’s name and finish time
for runner in results:
print(runner[0], runner[2])
Or
for runner in results:
name, country, time = runner
print(name, time)
CSE 160: Section 8
Problem 5
Part B. Find the fastest runner
CSE 160: Section 8
Problem 5 (Solution)
Part B. Find the fastest runner
fastest = results[0]
for runner in results:
if runner[2] < fastest[2]:
fastest = runner
print(fastest[0])
CSE 160: Section 8
Exit Ticket!
Write a function called sum_dict(nested_dict) that takes a dictionary of dictionaries and creates a single dictionary containing the sums of values with the same key in the given dictionaries.
Example:
{"dict_1" : {"b": 10, "a": 5, "c": 90},
"dict_2" : {"b": 78, "a": 45},
"dict_3" : {"a": 90, "c": 10}}
Should return:
{"b": 88, "a": 140, "c": 100}
CSE 160: Section 8
Exit Ticket! (Solution)
def sum_dict(nested_dict):
totals = {}
for name in nested_dict:
inner_dict = nested_dict[name]
for key in inner_dict:
if key in totals:
totals[key] += inner_dict[key]
else:
totals[key] = inner_dict[key]
return totals
CSE 160: Section 8
Problem 6
Write a function called analyze_scores(score_list) that takes in one parameter score_list, which is a list of student scores. The function should find the highest score (highest_score), the lowest score (lowest_score) and the number of scores that are at least 80 (count_80_or_more).
The function must return all three values as a tuple in this order:
(highest_score, lowest_score, count_80_or_more)
Example call to function:
scores = [88, 72, 90, 65, 78, 94, 55, 83, 100, 67, 81]
highest_score, lowest_score, count_80_or_more = analyze_scores(scores)
Expected output:
(100, 55, 6)
CSE 160: Section 8
Problem 6 (Solution)
def analyze_scores(score_list):
highest_score = score_list[0]
lowest_score = score_list[0]
count_80_or_more = 0
for score in score_list:
if score > highest_score:
highest_score = score
if score < lowest_score:
lowest_score = score
if score >= 80:
count_80_or_more += 1
return highest_score, lowest_score, count_80_or_more
CSE 160: Section 8
Problem 4
Write a function called reformat_dict(dict_list, new_key) that when given a list of dictionaries returns a dictionary of dictionaries with the keys being the value of new_key in each dictionary and the value being a dictionary with the rest of the key-value pairs besides new_key.
Example:
nested_dict = [{"County": "King", "Population": 2269675, "Temperature": 57}, {"County": "Pierce", "Population": 921130, "Temperature": 61}, {"County": "Snohomish", "Population": 827957, "Temperature": 53}]
Should return:
{'King' : {'Population' : 2269675, 'Temperature' : 57},
'Pierce' : {'Population' : 921130 , 'Temperature' : 61},
'Snohomish' : {'Population' : 827957 , "Temperature" : 53}}
CSE 160: Section 8
Problem 4 (Solution)
def reformat_dict(dict_list, new_key):
result = {}
for dictionary in dict_list:
inner_dict = {}
for key in dictionary:
if key != new_key:
inner_dict[key] = dictionary[key]
result[dictionary[new_key]] = inner_dict
return result
CSE 160: Section 8
Problem 1
Create a function called get_squares (number_list) that accepts a list of numbers and returns a dictionary mapping each number in the list to its square.
Ex: get_squares([1, 4, 4]) should return {1:1, 4:16}
CSE 160: Section 8
Problem 1 (Solution)
Create a function called get_squares (number_list) that accepts a list of numbers and returns a dictionary mapping each number in the list to its square.
Ex: get_squares([1, 4, 4]) should return {1:1, 4:16}
def get_squares(number_list):
squares = {}
for number in number_list:
squares[number] = number ** 2
return squares
CSE 160: Section 8
Problem 2
Write coldest_city (city temperatures) that takes in a dictionary and return the city (key) with the lowest temperature (value).
Ex: city_temperatures = {'Seattle': 36, 'Cupertino' :39, 'New York':57} coldest_city(city_temperatures) returns "Seattle"
CSE 160: Section 8
Problem 2 (Solution)
Write coldest_city (city temperatures) that takes in a dictionary and return the city (key) with the lowest temperature (value).
Ex: city_temperatures = {'Seattle': 36, 'Cupertino' :39, 'New York':57} coldest_city(city_temperatures) returns "Seattle"
def coldest_city(city_temperatures):
coldest = None
for city in city_temperatures:
if coldest is None:
coldest = city
elif city_temperatures[city] < city_temperatures[coldest]:
coldest = city
return coldest
CSE 160: Section 8
Thanks for Coming!
CSE 160: Section 8