Dictionaries

A dictionary stores pairs. Each pair has a key and a value. You use the key to get its value directly, so you do not need to know a position, as you would with a list.

rooms = {"studio": "open", "lab": "closed"}

rooms["lab"] = "open"
rooms["library"] = "closed"

print(rooms["lab"])
print(rooms)

Output:

open
{'studio': 'open', 'lab': 'open', 'library': 'closed'}

Put a key in square brackets to read its value or to set it. If the key already exists, the new value replaces the old one. If the key is new, Python adds a new pair. In the example, "lab" changes from closed to open, and "library" is added as a new pair.

A dictionary keeps its pairs in the order you added them. If you use brackets with a key that does not exist, you get a KeyError.

A key must be hashable. For now, think of this as a value that cannot change, such as a string or a number. A list can change, so it cannot be a key. If you try, Python raises TypeError: unhashable type: 'list'. A tuple can be a key, but only if everything inside it is hashable too. A value can be of any type.

In the exercise, look up a product and update the stock.