Recall how we were able to associate kids with their favourite thing about Halloween on the midterm: we used two parallel lists:
kids = ["Bob", "Dorothy", "Alice"]
faves = ["candy", "costumes", "midterms"]
We said that the favourite of kids[i] is faves[i].
Dictionaries provide us with a better way to accomplish the same thing. Here is how things would work:
faves = {"Bob": "candy", "Dorothy": "costumes", "Alice": "midterms"}
faves["Alice"]
"Bob", "Dorothy", and "Alice" are called keys. "candy", "costumes", and "midterms" are called values. We can access the value associted with the key k in a dictionary d using d[k]. That is what we do when we go faves["Alice"].
The dictionary faves is defined inside the curly braces, with keys and values separated by :, and with entries (i.e., key-value pairs) separated by commas.
Let's define a new dictionary, grades.
grades = {"PHY": 90, "CSC": 85, "CIV": 100, "ESC": 85}
We can modify existing values like this:
grades["CSC"] = 84
grades
We can also add entries, like this:
grades["MAT"] = 87
grades
Note that this is not similar to what can be done with lists: if an index does not exist in a list, we cannot add a value at that index:
L = [4, 5, 6]
L[100] = 10
Let's store the UofT endowment (in millions of dollars) in different years
endowment = {2012: 1518.2, 2014: 1881.7, 2015: 2142.5, 2016: 2097.1}
Note that we could use a list, but that would require us to also have endowment[0], endowment[1], etc.
Back to grades:
grades
We don't have to have all the values (or all the keys) be the same type. For example, we can go
grades["CSC"] = {"MT": 50, "Exam": 100, "Proj": 95}
grades
Keys in a dictionary have to be immutable. The following doesn't work:
L = [1, 2]
grades[L] = 5
Why not? Basically, it's unclear what should happen if we go L[0] = 15. Should grades[L] be the same, or hsould 5 always be grades[[1, 2]]? We could make the choice, in principle, but, for various reasons, Python simply doesn't allow for keys to be mutable.
Here is how you can get the list of all the keys in a dictionary:
list(endowment.keys())
All the values:
list(endowment.values())
Note that the keys and the values are given in no particular order. We can go through all the keys, and all the values, using for-loops:
for year in endowment.keys():
print(year)
for year in endowment: #get all the keys, in some order
print(year)
for amt in endowment.values():
print(amt)
You can also get the items in a dictionary -- those are the key-value pairs, as tuples:
grades = {"CSC": 87, "CIV": 100, "MAT": 95, "ESC": 95}
list(grades.items())
We can iterate through the keys, as we saw above:
for subj in grades:
print("I got", grades[subj], "in", subj)
We can also iterate through the items:
for subj, grade in grades.items():
print("I got", grade, "in", subj)
Here, we unpacked each item into subj and grade.
Again, note that when using a for-loop, the keys/items are not guaranteed to come in any particular order.