…
…
Python Programming Fundamentals · Lesson 26 / 40 · Dictionaries
PreviewIn this lesson you will
in and get(key, default) without crashing when a key is missingYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
At Corner Café, the product names were kept in one list and the prices in another. While adding a new product to the menu, Ada forgot to update the price list, and the register program silently lost that product. In this lesson you will keep each product with its price and its stock count in one place, and you will write functions that read and remove stock safely.
By the end of the lesson, the program you write will remove an item from a stock dictionary, leave the stock alone when it is not enough, delete an item that runs out, and not crash when someone asks for an item that is not on the menu at all:
OutputTrue
False
{'latte': 10, 'water': 6}
Tea stock: 0In this lesson you will:
in and get) inside functions, so the program does not crash when a key is missing.In lesson 24 we kept products and prices in two separate lists and matched them with zip: items = ["latte", "cookie", "tea"] and prices = [4.25, 2.00, 1.25]. This setup works as long as the two lists stay the same length. Ada added "water" to the menu but forgot to write 0.75 in the price list. Because zip stops when the shorter list ends, water silently dropped off the menu; the program did not even raise an error. On top of that, to answer "what is the price of a latte?", you first had to find the position of latte in the list, and then look at the same position in the price list.
What we want is simple: say the name of the product and get its price. The name and the value should sit in the same place, tied to each other. In Python, the structure that does this is called a dictionary (dict for short).
A dictionary is written with curly braces. Each element inside is a key: value pair, and pairs are separated by commas. Corner Café's menu looks like this: menu = {"latte": 4.25, "cookie": 2.00, "tea": 1.25}. Here "latte" is a key and 4.25 is its value. Keys are mostly strings; values can be of any type: a number, a string, a list. An empty dictionary is created with {}.
To read a value, you open square brackets next to the name of the dictionary and write the key: menu["latte"]. In a list you wrote a position number in the square brackets; in a dictionary you write the name. len(menu) gives how many pairs the dictionary has.
Example 1 (case): Reading from the menu
menu = {"latte": 4.25, "cookie": 2.00, "tea": 1.25}
print(menu["latte"])
print(len(menu))
print("water" in menu, 4.25 in menu)Output4.25
3
False FalseThe first line printed the price of the latte, and the second line printed the number of pairs. The third line has in, which you know from lesson 23: there is no water on the menu, so False. The second False may look surprising, because there is a $4.25 product on the menu. You will see the reason in section 5.
So what happens when you ask for a product that is not on the menu? Python stops and shows you a new kind of error that you will meet together with dictionaries:
menu = {"latte": 4.25, "cookie": 2.00, "tea": 1.25}
print(menu["mocha"])Error:
OutputTraceback (most recent call last):
File "<code>", line 2, in <module>
print(menu["mocha"])
~~~~^^^^^^^^^
KeyError: 'mocha'Use the reading routine from lesson 5: look at the last line first. The type is KeyError, a "key error". The explanation part contains only the key that was searched for: 'mocha'. The message means "this key is not in the dictionary". line 2 shows the line where the error happened, and the ^ marks show which part of that line: while reading menu["mocha"]. When you see this error, you check two things: how you wrote the key you are looking for, and how it is written in the dictionary.
A dictionary has no position number, that is, no index. If you write menu[0] out of the habit from lists, Python does not give you the first product. It looks for 0 as a key, cannot find it, and raises KeyError: 0. The missing quotes in the message tell you that the key searched for is a number, not a string.
Should you use a list or a dictionary? Ask yourself this question: will I reach the value with a position number or with a name? The products in a customer's cart are in order, and the same product can appear twice; this is a list. Each product on the menu has a single price, and you reach the price with the name of the product; this is a dictionary. Match the situations below to the right structure.
Which structure do you use for each situation?
For each row, pick its match from the list, then check.
There is no separate method for adding a new pair to a dictionary. You write an assignment: stock["cookie"] = 12. The same syntax does two different jobs. If the key is not in the dictionary, it adds a new pair; if it is, it throws away the old value and writes the new one, that is, it updates. Python first looks for the key and decides according to the result. Reading a key that does not exist raises an error, but assigning to a key that does not exist does not.
The reason is a rule: in a dictionary, each key appears only once; keys are unique. Even if you write {"latte": 4.25, "latte": 4.50}, only one latte stays in the dictionary, and its value is the last one written, 4.5. So you can assign without worrying "is there a latte already?"; if there is, it gets updated.
Augmented assignment also works on a key whose value is a number: stock["latte"] -= 2 reduces the stock of latte by two. This line first reads the value of stock["latte"], so it raises KeyError if the key does not exist.
There are two ways to delete. del stock["tea"] deletes the tea pair completely; del also works on a list (del cart[0] deletes the first element). stock.pop("cookie") deletes the pair and returns the deleted value, just like the pop method of a list in lesson 23. The only difference: in a list you gave pop a position number, in a dictionary you give a key. Use pop if you need the deleted value, and del if you do not.
Example 2 (case): Updating the stock dictionary
stock = {"latte": 10, "tea": 30}
stock["cookie"] = 12
stock["latte"] -= 2
del stock["tea"]
print(stock)
removed = stock.pop("cookie")
print(stock, removed)Output{'latte': 8, 'cookie': 12}
{'latte': 8} 12The second line added the cookie, the third line lowered the latte from 10 to 8, and the fourth line deleted the tea. pop took the cookie out of the dictionary and put its value (12) into the removed box. The pairs of a dictionary are printed in the order they were added; the cookie was added last, so it appears at the end.
Two more methods make your work easier. If the new stock from the supplier is in another dictionary, instead of writing a separate assignment for each product you write stock.update(arrived): each pair in the arrived dictionary is processed as if an assignment had been made one by one. If the key exists in stock, its value is updated; if not, it is added. If you want to empty the dictionary at the end of the day, stock.clear() deletes all the pairs; the dictionary stays in place but becomes empty. Both change the dictionary in place and return None, like the list methods in lesson 23; if you write stock = stock.update(arrived), you lose the dictionary.
stock = {"latte": 8, "tea": 30}
arrived = {"tea": 40, "water": 24}
stock.update(arrived)
print(stock)
stock.clear()
print(stock, len(stock))Output{'latte': 8, 'tea': 40, 'water': 24}
{} 0update changed the value of tea from 30 to 40, added water as a new pair, and did not touch latte. After clear, no pair was left in the dictionary.
Let's collect all the operations in a table. Pay attention to the last column: what happens if the key does not exist?
| Operation | Syntax | If the key does not exist |
|---|---|---|
| Read | menu["latte"] | KeyError |
| Safe read | menu.get("latte") | returns None |
| Read with a default | menu.get("latte", 0) | returns 0 |
| Add / update | menu["latte"] = 4.50 | a new pair is added |
| Delete | del menu["latte"] | KeyError |
| Take out | menu.pop("latte") | KeyError |
| Add / update in bulk |
Now touch a stock dictionary yourself (the interactive block works with integers, so this one holds stock counts). Press each button and look at both the boxes and the Python answer in the log. stock["mocha"] and stock[0] raise errors on purpose; compare them with the get lines.
Touch the stock: when does an assignment add, and when does it update? Which reads raise an error?
Press an operation; predict what Python will say first.
No operations yet. Press a button above.
Now follow the same operations inside a program. In the second line, see that a new pair is added to the box; in the third line, see that the existing tea changes. Then use "Change the code", write "latte" instead of "mocha", and look at what the price box takes.
Run the code line by line: see which line runs next, the variable boxes and the output.
menu = {"tea": 1.25, "latte": 4.25}
menu["bagel"] = 1.50
menu["tea"] = 1.40
price = menu.get("mocha", 0)
print(menu)
print(price, "latte" in menu)At a real register, the two structures work side by side. The cart is a list: whatever the customer asked for, in the order they asked, with repeats. The prices are a dictionary: one price for each product. To get the bill, you walk through the cart, read the price of each product from the menu, and add it up. This is the basic job of the café program.
Example 3 (case): The total of a cart
menu = {"latte": 4.25, "cookie": 2.00, "tea": 1.25, "water": 0.75}
cart = ["latte", "tea", "tea"]
total = 0
for item in cart:
total += menu[item]
print("Total:", total)OutputTotal: 6.75In each turn, the loop takes a product name from the cart and reads its price with menu[item]: 4.25, 1.25, 1.25. Tea is in the cart twice, so it is added twice. In the dictionary, however, tea stands only once. But what if the cart had a product that is not on the menu? Predict.
What happens when this code runs?
menu = {"tea": 1.25}
print(menu["latte"])in and getWhen a product that is not on the menu enters the cart, the whole program crashing is not acceptable. The line at the register should not stop because of a mocha. There are two ways to keep the program alive when a key is missing.
The first way is asking first: if item in menu:. In a dictionary, in looks only at the keys. "tea" in menu is true, but 1.25 in menu is false, because 1.25 is not a key, it is a value. The second False in Example 1 came from here.
The second way is the get method. menu.get("mocha") does not raise an error when the key is missing; it returns None. If you give a second value, for example menu.get("mocha", 0), it returns that default when the key is missing. If the key exists, both give the real value. get only reads; it adds nothing to the dictionary.
Example 4 (case): Reading with `get`
menu = {"latte": 4.25, "tea": 1.25}
print(menu.get("tea"))
print(menu.get("mocha"))
print(menu.get("mocha", 0))
print(menu)Output1.25
None
0
{'latte': 4.25, 'tea': 1.25}Look at the last line: we asked for mocha twice, but there are still two products on the menu. get adds nothing.
Which one should you use when? If you will do something different when the key is missing, for example tell the customer "Not on the menu", ask with in. If you will continue with a value when the key is missing, for example count the missing one as 0, give a default with get. Try both in the cell below.
Try it now· not graded; doesn't affect progress
Both solutions find the total 4.25. get continues silently; in can tell the customer what is missing. Now check once more what in looks at.
What does this code print?
menu = {"latte": 4.25, "tea": 1.25}
print("tea" in menu, 1.25 in menu)A dictionary is not only for menus. It works anywhere you need to "find one thing by another". Let a city bus keep a balance by card number. The card numbers are written as strings ("1001"), because you do not calculate with a number; the number is used only like a name. The rule is simple: if you will not add or subtract with a number, keep it as a string.
Example 5 (outside the case): Card balances
cards = {"1001": 25, "1002": 6}
cards["1003"] = 0
cards["1002"] += 50
print(cards.get("1001", 0), cards.get("9999", 0))
print(cards)Output25 0
{'1001': 25, '1002': 56, '1003': 0}The new card was added with a balance of 0, and $50 was loaded onto card 1002. When the missing card 9999 was asked for, the program did not crash, the default 0 came back, and the card was not added to the dictionary.
Now let's write the target program of the lesson. We keep the stock in a dictionary and write three functions for three jobs: read, add, remove. read_stock counts a missing product as 0. add_stock adds to the product if it exists, and opens a new key if it does not; both happen with the same assignment line. take_from_stock does not touch the dictionary and returns False if the stock is not enough; if it is enough, it removes the amount, deletes a product that falls to zero, and returns True. The functions change the dictionary inside. Remember from lesson 25: when a mutable structure is given to a function, the change is also visible in the dictionary outside.
Example 6 (case): The target program of the lesson
def read_stock(stock, item): # 1. Count a missing item as 0 return stock.get(item, 0) def add_stock(stock, item, amount): # 2. Add to it if it exists, open a new key if not stock[item] = read_stock(stock, item) + amount def take_from_stock(stock, item, amount): # 3. Do not touch the stock if there is not enough current = read_stock(stock, item) if amount > current: return False # 4. Remove it; delete the key if it falls to zero stock[item] = current - amount if stock[item] == 0: del stock[item] return True stock = {"latte": 10, "cookie": 4} add_stock(stock, "water", 6) print(take_from_stock(stock, "cookie", 4)) print(take_from_stock(stock, "latte", 12)) print(stock) print("Tea stock:", read_stock(stock, "tea"))
OutputTrue
False
{'latte': 10, 'water': 6}
Tea stock: 0When 4 cookies were removed, the stock fell to zero and the key was deleted: True. 12 lattes were asked for and there were 10 in stock; the function returned False without touching the dictionary. Water came in as a new key with add_stock. When tea, which was never there, was asked for, the program did not crash either.
Change the value of amount and look at which lines run. When you choose 10, the del line comes into play; when you choose 12, the function ends at the first return.
How many lattes are we removing? Change the value of amount; which lines run, and how does the dictionary change?
Pick a value; predict the output first, then look.
1def read_stock(stock, item):2 return stock.get(item, 0)34def take_from_stock(stock, item, amount):5 current = read_stock(stock, item)6 if amount > current:7 return False8 stock[item] = current - amount9 if stock[item] == 0:10 del stock[item]11 return True1213stock = {"latte": 10, "cookie": 4}14amount = 215print(take_from_stock(stock, "latte", amount), stock)
True {'latte': 8, 'cookie': 4}Faded lines didn't run with this value. When 2 lattes are removed, the stock becomes 8. When 10 are removed, the stock falls to 0 and the del line deletes latte from the dictionary. When 12 are asked for, the stock is not enough: the function ends at the return False line, and the dictionary is never touched.
Now build the take_from_stock function line by line yourself.
Put the lines of the take_from_stock function in the right order with their indentation.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
One last trap: keys are case sensitive. "Latte" and "latte" are two different keys; if "latte" is in the dictionary and you write menu["Latte"], you get KeyError: 'Latte'. The same is true for spaces: "latte " is also a different key. Before you look up a product name that comes from a customer or a file, clean it with strip() and lower() from lesson 21: menu[order.strip().lower()].
Finally, a note about speed. A dictionary finds the value of a key almost instantly even when it has thousands of pairs; it does not look from the beginning to the end like searching in a list. That is why a dictionary is the natural choice for "find by name": the price by product name, the bill by table number, the balance by card number.
We build a small English-Spanish word dictionary. We first clean the incoming words, then look them up with get; for an unknown word we print ?.
words = {"coffee": "café", "tea": "té", "water": "agua"}
incoming = ["Tea", "milk", "water "]
for word in incoming:
clean = word.strip().lower()
print(word.strip(), "->", words.get(clean, "?"))OutputTea -> té
milk -> ?
water -> agua"Tea" came with an uppercase letter and "water " came with a space at the end; if they had not been cleaned, neither would have been found. "milk" is not in the dictionary, so the default "?" came back. The default does not have to be a number; it can be a string too.
For each product in the cart, we remove one unit from the stock. For a product whose stock has run out or that does not exist at all, we print "sold out".
stock = {: 2, : 5}
cart = [, , , , ]
item cart:
current = stock.get(item, 0)
current > 0:
stock[item] = current - 1
(item, )
:
(item, )
(stock)Writing the key differently. If the key in the dictionary is "latte" and you read it with an uppercase letter, Python stops:
menu = {"latte": 4.25, "tea": 1.25}
print(menu["Latte"])Error:
OutputTraceback (most recent call last):
File "<code>", line 2, in <module>
print(menu["Latte"])
~~~~^^^^^^^^^
KeyError: 'Latte'The KeyError message writes the key that was searched for exactly: 'Latte'. Compare it letter by letter with the key in the dictionary; the problem is the uppercase L. The right way: write the key as it is in the dictionary, clean a name that comes from outside with strip().lower(), and for keys that might not be in the dictionary use if item in menu: or menu.get(item, 0).
{key: value} pairs; you reach a value with the key, not a position number (menu["latte"]), a missing key raises KeyError, and a dictionary has no index.dictionary[key] = value adds if the key does not exist and updates if it does (keys are unique); del deletes a pair, pop deletes it and returns the value; update adds or updates the pairs of another dictionary in bulk, clear deletes all the pairs.in (it looks only at keys) or use get(key, default); get does not change the dictionary, and if you will calculate with the result, give a default.Next lesson: How do we walk through all the products of a dictionary, and how do we count the orders that arrive during the day, product by product? In the next lesson we will go through a dictionary and keep a tally.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
menu.update(new) |
| new pairs are added |
| Delete everything | menu.clear() | the dictionary becomes empty |
| Is it there? | "latte" in menu | False |
Outputlatte served
tea served
latte served
latte sold out
mocha sold out
{'latte': 0, 'tea': 4}At the third latte, the stock fell to 0; when the fourth latte was asked for, get gave 0 and "sold out" was printed. Mocha was never there; thanks to get(item, 0) the program did not crash, and mocha was not added to the dictionary. This loop does not delete the latte that fell to zero; the take_from_stock in the target program did. Which one you choose depends on the café's rule.