Python Arena
Step 2 of 6

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])
Output
1 Monday
2 Tuesday
3 Wednesday

With 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])
Output
{'Ada': [9, 7], 'Max': [6, 8], 'Lin': []}
9

grades["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:

In the Python interpreter
>>> stock = {"apples": 5}
>>> stock["apples"] = 3
>>> stock
{'apples': 3}
>>> stock["apples"] += 10
>>> stock["apples"]
13

stock["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"])
Output
{'Ada': 1, 'Max': 2, 'Lin': 3}
3

Keys 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"
Python stops with
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.

Your task

Challenge 1 of 3

Write a function word_lengths(words) that returns a dictionary in which each word of the list is a key and its length is the value. For example, word_lengths(["sun", "moon", "sky"]) returns {'sun': 3, 'moon': 4, 'sky': 3}. If a word is in the list twice, it's in the dictionary once.

Challenge 2

What does this program print? Type each line it prints.

Challenge 3

Write a function divisor_table(n) that returns a dictionary whose keys are the numbers from 1 to n. The value of each key is a list of the numbers that divide it evenly, from smallest to largest.

For example, divisor_table(4) returns {1: [1], 2: [1, 2], 3: [1, 3], 4: [1, 2, 4]}.