Python 3D Academyবাংলা

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"]:

  1. Python takes the key "Bo".
  2. It goes straight to the locker labelled "Bo".
  3. It gives back what's inside: 11.
ages = {"Ana": 9, "Bo": 11}
print(ages["Bo"])
print(len(ages))
print(ages)
A dictionary keeps its pairs in the order you added them.

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"] gives KeyError: 'Cy' (above). Check with in, or use get (next lesson).
  • in looks at keys. 9 in {"Ana": 9} is False: 9 is a value, not a key.
  • A list as a key. {[1]: 2} gives TypeError: 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

  1. What does this print?

    d = {"a": 1, "b": 2}
    print(d["b"])
  2. What does this print?

    d = {"x": 10}
    print("x" in d, 10 in d)
  3. What does this print?

    print(len({"a": 1, "b": 2, "c": 3}))
  4. What happens with d["zzz"] when "zzz" isn't a key?

    • A KeyError
    • It gives None
    • It adds "zzz" to the dictionary
  5. What does this print?

    d = {1: "one", 2: "two"}
    print(d[2])
  6. Which line has a mistake?

    colors = {"sky": "blue"}
    print(colors["grass"])

Coding tasks

  1. Make a dictionary called capitals where "France" leads to "Paris" and "Japan" leads to "Tokyo". Then print the capital of Japan.

  2. The shop's prices are prices = {"apple": 30, "banana": 10, "kiwi": 15}. Ask for a fruit and print its price, or not sold here if the shop doesn't sell it.

  3. Ask for a whole number. Use the dictionary {1: "one", 2: "two", 3: "three"} to print its name, or ? for any other number.