Python Arena
Step 1 of 6

Keys and values

A list finds its items by position: 0, 1, 2 and so on. Often you'd rather find a value by a name: the price of a coffee, the phone number of Ada. A dictionary stores pairs of a key and a value, and you find each value by its key, the way you look up a word in a real dictionary to find what it means.

prices = {}
prices["coffee"] = 2.5
prices["tea"] = 2.0
prices["cake"] = 3.75

print(prices)
print(len(prices))
print(prices["tea"])
Output
{'coffee': 2.5, 'tea': 2.0, 'cake': 3.75}
3
2.0
  • {} is an empty dictionary.
  • prices["coffee"] = 2.5 adds the key "coffee" with the value 2.5.
  • prices["tea"], with a key in square brackets, gives that key's value.
  • len counts the pairs, and print shows them all, in curly braces, with a colon between each key and its value.

You can also write the pairs right away, in that same form:

In the Python interpreter
>>> capitals = {"Finland": "Helsinki", "Peru": "Lima"}
>>> capitals["Peru"]
'Lima'
>>> capitals["Chile"] = "Santiago"
>>> capitals
{'Finland': 'Helsinki', 'Peru': 'Lima', 'Chile': 'Santiago'}
>>> type(capitals)
<class 'dict'>

Python's name for the dictionary type is dict.

Is the key there?

Asking for a key that isn't in the dictionary stops the program with a KeyError, which names the missing key:

prices = {"coffee": 2.5, "tea": 2.0}
print(prices["juice"])
Python stops with
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(prices["juice"])
          ~~~~~~^^^^^^^^^
KeyError: 'juice'

The in operator checks first. With a dictionary, it looks at the keys only, not at the values:

In the Python interpreter
>>> prices = {"coffee": 2.5, "tea": 2.0}
>>> "tea" in prices
True
>>> 2.5 in prices
False

Together, in and a lookup make a program that finds things for the user:

prices = {"coffee": 2.5, "tea": 2.0, "cake": 3.75}

item = input("What would you like? ")
if item in prices:
    print(f"That's {prices[item]:.2f} euros.")
else:
    print("Sorry, we don't have that.")
Input
cake
Output
What would you like? cake
That's 3.75 euros.

Your task

Challenge 1 of 3

Fill in the blanks so the program adds a spider, with 8 legs, to the dictionary. Then it prints the number of animals in the dictionary and the legs of a bird and a spider together:

3
10

Challenge 2

A cinema keeps its showtimes in a dictionary. Complete the program: it asks for a movie and prints when it starts, or No such movie today when the movie isn't in the dictionary. Use the prompt Movie: exactly. An example run:

Movie: Tiny Giants
Tiny Giants starts at 16:15

Challenge 3

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