Making dictionaries
🌍 In real life. At a railway station's left-luggage room, each locker has a label, and you open a locker by its label, not by counting along the row. A dictionary of words works the same way: you find "apple" by the word itself and read its meaning.
A Python dictionary is a wall of labelled lockers: you look things up by name.
The idea in one sentence: a dictionary stores key: value pairs, and d[key] opens the locker with that key and gives you its value.
Its words:
- key: the label you look up by, like
"Bo"; each key appears only once - value: what's stored under the key, like
11 - pair (or item): one key with its value
{key: value, key: value}: how you write a dictionary
Step by step, for ages["Bo"]:
- Python takes the key
"Bo". - It goes straight to the locker labelled
"Bo". - It gives back what's inside:
11.
ages = {"Ana": 9, "Bo": 11}
print(ages["Bo"])
print(len(ages))
print(ages)How Python does it, and what it costs. A dictionary finds a key the same way a set finds a value (Chapter 10): it works out the key's hash, which points straight at the right locker. So ages["Bo"] and "Bo" in ages take about the same time whether the dictionary has two keys or two million. A list of pairs would have to be searched one pair at a time.
That's also why keys must be values that never change, like strings, numbers and tuples, and why each key appears only once. Values can be anything, even lists.
Asking for a key that isn't there stops the program with a KeyError. key in ages checks first: in looks at the keys, not the values.
ages = {"Ana": 9, "Bo": 11}
print(ages["Cy"])prices = {"apple": 30, "kiwi": 15}
item = input("Fruit: ")
if item in prices:
print(item, "costs", prices[item])
else:
print("not sold here")numbers = {1: "one", 2: "two"}
print(numbers[2])
team = {"red": ["Ana", "Bo"], "blue": ["Cy"]}
print(team["red"])Mistakes and edge cases.
- A missing key.
ages["Cy"]givesKeyError: 'Cy'(above). Check within, or useget(next lesson). - in looks at keys.
9 in {"Ana": 9}isFalse: 9 is a value, not a key. - A list as a key.
{[1]: 2}givesTypeError: cannot use 'list' as a dict key (unhashable type: 'list'). Use a tuple. - The same key twice.
{"a": 1, "a": 2}keeps only the last one:{'a': 2}, with no error. - Indexing by position.
ages[0]looks for a key 0, not the first pair.
Quiz
What does this print?
d = {"a": 1, "b": 2} print(d["b"])What does this print?
d = {"x": 10} print("x" in d, 10 in d)What does this print?
print(len({"a": 1, "b": 2, "c": 3}))What happens with
d["zzz"]when "zzz" isn't a key?- A KeyError
- It gives None
- It adds "zzz" to the dictionary
What does this print?
d = {1: "one", 2: "two"} print(d[2])Which line has a mistake?
colors = {"sky": "blue"} print(colors["grass"])
Coding tasks
Make a dictionary called
capitalswhere"France"leads to"Paris"and"Japan"leads to"Tokyo". Then print the capital of Japan.The shop's prices are
prices = {"apple": 30, "banana": 10, "kiwi": 15}. Ask for a fruit and print its price, ornot sold hereif the shop doesn't sell it.Ask for a whole number. Use the dictionary
{1: "one", 2: "two", 3: "three"}to print its name, or?for any other number.