What a dictionary can hold
The values in a dictionary can be of any type: numbers, strings, lists, even other dictionaries. Keys are often strings, but numbers work just as well. Here the keys are numbers:
days = {1: "Monday", 2: "Tuesday", 3: "Wednesday"}
for number in range(1, 4):
print(number, days[number])
1 Monday
2 Tuesday
3 WednesdayWith lists as values, each key can have many values. A list in a dictionary is changed like any other list:
grades = {"Ada": [9, 7], "Max": [6]}
grades["Max"].append(8)
grades["Lin"] = []
print(grades)
print(grades["Ada"][0])
{'Ada': [9, 7], 'Max': [6, 8], 'Lin': []}
9grades["Max"] is a list, and .append(8) changes that list inside the dictionary. grades["Ada"][0] reads from left to right: the value of "Ada", then the item at index 0 of that list.
One value per key
A key is in a dictionary only once. Assigning to a key that's already there replaces its value. That's also how you update a value:
>>> stock = {"apples": 5}
>>> stock["apples"] = 3
>>> stock
{'apples': 3}
>>> stock["apples"] += 10
>>> stock["apples"]
13stock["apples"] += 10 reads the old value, adds 10 and stores the result under the same key. A value, on the other hand, can be stored under many keys: in {"Ada": 9, "Max": 9}, both keys have the value 9.
A loop can fill a dictionary, one key at a time:
names = ["Ada", "Max", "Lin"]
seat_of = {}
for i in range(len(names)):
seat_of[names[i]] = i + 1
print(seat_of)
print(seat_of["Lin"])
{'Ada': 1, 'Max': 2, 'Lin': 3}
3Keys must not change
A key must be immutable. Numbers, strings and Booleans work (and so do tuples, which the last module of this part shows). A list can't be a key, because it could change after it went into the dictionary:
places = {}
places[[60, 24]] = "Helsinki"
Traceback (most recent call last):
File "main.py", line 2, in <module>
places[[60, 24]] = "Helsinki"
~~~~~~^^^^^^^^^^
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')To find a key fast, Python turns it into a number called a hash, and that number must never change. A list's contents can change, so a list is "unhashable". Values have no such rule.