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"])
{'coffee': 2.5, 'tea': 2.0, 'cake': 3.75}
3
2.0{}is an empty dictionary.prices["coffee"] = 2.5adds the key"coffee"with the value 2.5.prices["tea"], with a key in square brackets, gives that key's value.lencounts the pairs, andprintshows 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:
>>> 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"])
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:
>>> prices = {"coffee": 2.5, "tea": 2.0}
>>> "tea" in prices
True
>>> 2.5 in prices
FalseTogether, 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.")
cakeWhat would you like? cake
That's 3.75 euros.