CSE 160 Section 7
Sets, Tuples & Nested Structures!
Logistics
Lecture Review: Sets
Sets
You can imagine a set that contains the values 1 through 6 like this:
1
2
3
4
5
6
Sets
You can imagine a set that contains the values 1 through 4 like this:
s = set([1, 2, 3, 4])
s = {1, 1, 1, 1, 1, 1, 2, 3, 4}
1
3
2
4
s = {1, 2, 3, 4}
s = set()
s.add(1)
s.add(2)
s.add(3)
s.add(4)
Add, Remove, and Discard
Say we have the set s that has elements 1, 2, 3, 4 inside
Add
1
3
2
4
Remove
Discard
Pop
Sets
Looping Through a Set
To see all elements in a set, we can loop through it
Would print 1, 2, 3, 4 in some random order
1
3
2
4
for element in s:
print(element)
Checking If Something Is In A Set
We can use in to see if an element is in a set
Returns True
Returns False
1
3
2
4
2 in s
6 in s
Set Operations
A | B
A & B
A - B
A ^ B
elements only in A
elements only in B
items in both
Set Operations
Set Operation | Code |
Adding values | my_set.add(val) |
Removing values | my_set.remove(val) #Value must already exist my_set.discard(val) #Value doesn’t need to exist |
Return a random element | my_set.pop() |
Return all values in both sets | set_1 | set_2 Or set_1.union(set_2) |
Return values found in both sets | set_1 & set_2 Or set_1.intersection(set_2) |
Return values only found in set_1 | set_1 - set_2 Or set_1.difference(set_2) |
Return values not found in both sets | set_1 ^ set_2 |
Set Practice Problem 1
Given two lists:
a = [10, 20, 30, 40]
b = [30, 40, 50, 60]
Write a program that prints the elements that are in a but not in b.
Set Practice Problem 2
Write a function called unique(original_list) that takes in a list of words and prints the unique words across all sentences in a set.�
For example, if a list was defined as below:
sentences = ["hello world", "hello python", "python is fun"]
Then unique(sentences) should output:
{“fun”, “is”, “hello”, “python”, “world”}
Lecture Review: Tuples
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) | ✅ | 🚫 |
put in a set | set().add(name) | 🚫 | ✅ |
use a dict keys | dict(name:val) | 🚫 | ✅ |
Making a Tuple
These are all ways to make tuples:
Note that to make a one element tuple you need to add a comma after the one value! (1) would not work!
t = tuple([1, 2, 3])
t = (1, 2, 3)
t = (1,)
Lecture Review: Nested Structures
Review of nested structures
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 |
Review of nested structures
Nested Lists
255 | 0 | 255 |
0 | 0 | 255 |
255 | 255 | 255 |
| | |
| | |
| | |
Dictionary with Lists as Values
{"p1": [10.0, 10.5, 9.9], "p2": [8.0, 9.5, 9.2], "p3": [8.0, 8.2, 10.1]}
Lists of Dictionaries
Nested Dictionaries
How would we represent this data in python?
| | |
| | |
| | |
Section Handout Problems
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
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
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 list 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}
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
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}}
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
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 contains the keys and the subsequent rows are the values of each dictionary. You may assume that the format will exactly follow the example 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"}]
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