Dictionaries: price tags for your data
A list is great when things are in a line. But a price isn't "the third thing." It belongs to a bake. A dictionary matches labels to values, like price tags in a shop.
The big idea
A dictionary stores pairs: a label, called a key, and the value that goes with it. You look a value up by its label.
See it in code
Curly brackets make a dictionary. Each pair is a label, a colon, then its value. To look one up, put the label in square brackets:
prices = {"cookies": 2, "cupcakes": 3, "brownies": 2}
print("Cupcakes cost $", prices["cupcakes"])Cupcakes cost $ 3
You didn't need to know where cupcakes sit in the dictionary. You asked by name, and got the value that belongs to that name.
Storing to a new label adds a tag. Storing to a label that's already there replaces its value. And in checks whether a label exists:
prices = {"cookies": 2, "cupcakes": 3, "brownies": 2}
prices["croissants"] = 4
prices["cookies"] = 3
print(prices)
print("Do we sell pie?", "pie" in prices){'cookies': 3, 'cupcakes': 3, 'brownies': 2, 'croissants': 4}
Do we sell pie? Falsein looks at the labels, not the values. There's no "pie" tag, so the answer is False.
A lookup can use a variable. Loop over an order, look up each bake's price, and add it to a running total:
prices = {"cookies": 3, "cupcakes": 3, "brownies": 2, "croissants": 4}
order = ["cookies", "croissants", "brownies", "cookies"]
total = 0
for item in order:
print(f"{item}: ${prices[item]}")
total = total + prices[item]
print(f"Order total: ${total}")cookies: $3 croissants: $4 brownies: $2 cookies: $3 Order total: $12
prices[item] looks up a different label on each trip. Change one price in the dictionary and every receipt follows.
Dictionaries hold anything you look up by name. A shop's stock by item. A word and its meaning. A player and their best score.
Try it yourself
Add "maple scones": 3 to prices and add "maple scones" to the order. Run it and check the total. Then loop over prices itself to print a price board.
The common mistake
Looking up a label that isn't there, or isn't spelled the same. prices["Cookies"] with a capital C stops with a KeyError. A label must match exactly, letter for letter.
What it unlocks
Dictionaries and lists work as a team: a list for the order, a dictionary for the prices. Put a lookup inside a function and you get a tidy price_each() recipe.