Previous Lecture Lecture 14 Next Lecture

Lecture 14, Thu 02/22

Nested Lists, More on Dictionaries

Recorded Lecture: 2_22_24

List Nesting

nestedList = [[1,2], [3,4,5], [6]]
print(nestedList) # [[1,2], [3,4,5], [6]]
print(nestedList[1]) # [3, 4, 5]
print(nestedList[1][2]) # 5
nestedList[1][2] = 500
print(nestedList[1][2]) # 500

y = [[1,2], [[3,4]], [5]]
print(y[0]) # [1, 2]
print(y[1]) # [[3, 4]]
print(y[1][1]) #ERROR!
print(y[1][0]) # [3, 4]
print(y[1][0][1]) # 4
nestedList = [[1,2], [3,4,5], [6]]
for i, element in enumerate(nestedList):
	for j, innerElement in enumerate(element):
		print(f"nestedList[{i}][{j}] =", nestedList[i][j])

More on Dictionaries

D = dict()
print(D)
D = dict(A=1, B=2) # converts identifiers to keys
print(D)
D = dict([['A', 1], ['B', 2]]) # converts collection of pairs
print(D)
D = {"CS8":[90, 85, 95, 100], "CS9":[85, 90, 95, 100]}
print(D) # {'CS8': [90, 85, 95, 100], 'CS9': [85, 90, 95, 100]}
print(D["CS8"]) # [90, 85, 95, 100]
print(D["CS8"][2]) # 95
D = {'A':1, 'B':2}
print(D.pop('A')) # 1
print(D) # {'B': 2}
print(D.pop('A')) # Error
print(D.pop('A', ':(')) # :( (No error)
D1 = {'A':1, 'B':2}
D2 = {'B':200, 'C':3}
print(D1.update(D2)) # None
print(D1) # {'A': 1, 'B': 200, 'C': 3}
print(D2) # {'B': 200, 'C': 3}
D = {'A':1, 'B':2}
print(D.get('A')) # 1
print(D.get('a')) # None
print(D.get('a', ":(")) # :(

Dictionary Views

# using .items() object view to iterate through key / value pairs
D = {"CS8": "Zoom", "CS9":"ILP", "CS16":"BUCHN"}
pairs = D.items()
print(pairs)

for key, value in pairs:
	print("Course: ", key, " | Location: ", value, sep="")

D["CS8"] = "HFH" # Change key’s value to HFH

for key, value in pairs:
	print("Course: ", key, " | Location: ", value, sep="") # change persists
# using .keys() object view to iterate through keys
D = {"CS8": "Zoom", "CS9":"ILP", "CS16":"BUCHN"}
keys = D.keys()
print(keys)

for key in keys:
	print("Course: ", key, " | Location: ", D[key], sep="")
# using .values() object view to iterate through values
D = {"CS8": "Zoom", "CS9":"ILP", "CS16":"BUCHN"}
values = D.values()
print(values)

print("Locations: ", end="")
for value in values:
	print(value, " ", end="")
print()

Dictionary Nesting

UCSB = {
	"CS8": {
		"Location": "Zoom",
		"Capacity": 300,
		"Quiz Grades": [20, 18, 19]
	},
	"MATH3A": {
		"Location": "BUCHN",
		"Capacity": 150,
		"Final Scores": [100, 100, 99, 100]
	}
}

print(UCSB.get("PSTAT120A")) # None
print(UCSB.get("CS8"))
print(UCSB.get("CS8").get("Quiz Grades")) # [20, 18, 19]
print(UCSB.get("CS8").get("Quiz Grades")[2]) # 19