…
…
Python Programming Fundamentals · Lesson 27 / 40 · Dictionaries
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The orders taken during the day are in a list: ["latte", "tea", "latte", "water", "latte", "tea"]. At the end of the day, Ada wants to see how many of each product were sold and which one sold the most. In this lesson you will learn to loop through a dictionary, and you will write functions that count the orders product by product and work out revenue per product.
The program you will write by the end of the lesson turns the day's orders into this table:
Outputlatte 3
tea 2
water 1
Top seller: latteIn lesson 12 you learned the counter and total patterns. If you tried to do this job with those patterns, you would need a separate counter variable for each product: latte_count, tea_count, water_count. When mocha joins the menu tomorrow, you would have to add a new variable and a new if to the code; with a menu of fifty products, this becomes impossible to manage. With a dictionary, one structure is enough no matter how many products there are: the product name is the key and its count is the value. When a new product arrives, a new key is added to the dictionary by itself, and you do not need to change the code.
In this lesson you will:
In lesson 26 you learned to read a single value from a dictionary with a key: menu["latte"]. But most of the time you do not want to do something with one product, you want to do it with all of them: print the whole menu, add up all the prices, find the most expensive product. For this you loop through the dictionary with a for loop. When you loop through a list, one element arrives on each turn; with a dictionary, you choose what you want to arrive: the keys, the values, or both together.
| Syntax | What does the loop variable get on each turn? | Example use |
|---|---|---|
for item in menu: | Key | List the product names |
for item in menu.keys(): | Key | The same, written more explicitly |
for price in menu.values(): | Value | Add up the prices |
for item, price in menu.items(): | Key and value (pair) | Print the product with its price |
The most important rule is in the first row of the table: looping through a dictionary directly gives you the keys. Since the main purpose of a dictionary is to reach a value with a key, Python puts the keys first when looping too. If you need the value, you can write menu[item] inside the loop, but if you need the key and the value together, items() is cleaner. On each turn, items() gives a (key, value) pair, and this pair is unpacked into two names, as in the zip loop in lesson 24: the name on the left gets the key, the name on the right gets the value.
values() is ideal for calculations with the values. The sum and max you used with lists in lesson 24 also work with menu.values(). sorted(menu) sorts the keys and returns them as a list; the dictionary itself is not sorted, and no new dictionary is created.
Example 1 (case): Looping through the menu
menu = {"latte": 4.25, "cookie": 2.00, "tea": 1.25}
for item, price in menu.items():
print(f"{item}: ${price:.2f}")
print("Price total:", sum(menu.values()))
print("Highest price:", max(menu.values()))
print(sorted(menu))Outputlatte: $4.25
cookie: $2.00
tea: $1.25
Price total: 7.5
Highest price: 4.25
['cookie', 'latte', 'tea']The loop gave the products in the order they were added to the dictionary. Look at the square brackets in the last line: sorted returned a list, and menu still stays in its old order. One more note: if you write print(menu.keys()), you see dict_keys([...]) on the screen; this is a special view that you can loop through but that is not a list. If you need a real list, you write list(menu.keys()).
Now test the point that is mixed up most often. Answer without running the code.
What does this loop print?
menu = {"tea": 1.25, "latte": 4.25}
for name in menu:
print(name)Every job has its own syntax. Below, match each job with the right syntax; there is also a trap option in the list.
For menu = {"latte": 4.25, "cookie": 2.00, "tea": 1.25}, which syntax does each job use?
For each row, pick its match from the list, then check.
Back to Ada's question: how many of each product were sold? We do not know in advance which products will come; the list has only today's sales. The solution is to start with an empty dictionary and run this line for every product in the list:
counts[item] = counts.get(item, 0) + 1
Read this line from right to left. counts.get(item, 0) gives the current count if the product was seen before, and 0 if it is seen for the first time. 1 is added to this value, and the result is written to the same key. When the first latte arrives, there is no latte in the dictionary: get returns 0, and latte becomes 0 + 1 = 1. When the second latte arrives, get returns 1, and latte becomes 1 + 1 = 2. In lesson 26 you ran this line once in the add_stock function; now you are putting the same line inside a loop.
Example 2 (case): Counting the orders
orders = ["latte", "tea", "latte", "water", "latte", "tea"] counts = {} for item in orders: counts[item] = counts.get(item, 0) + 1 print(counts)
Output{'latte': 3, 'tea': 2, 'water': 1}The keys entered the dictionary in the order the products were first seen: latte first, then tea, and water last. We did not write the product names by hand anywhere in the code; the lines of the tally opened by themselves from the data.
Step through the code below. See that the counts box becomes {'tea': 1}, {'tea': 1, 'latte': 1}, and {'tea': 2, 'latte': 1} in three turns. Then use "Change the code" to add a "water" to the list and step through it again.
Run the code line by line: see which line runs next, the variable boxes and the output.
order = ["tea", "latte", "tea"] counts = {} for item in order: counts[item] = counts.get(item, 0) + 1 for item, count in counts.items(): print(item, count)
If we put the pattern into a function, we can call it with each day's list. In the block below, change the orders value and look at the output. Pay special attention to the empty list: the loop body never runs (that line stays dimmed), and the function returns an empty dictionary.
Which orders are we counting? Change the orders value.
Pick a value; predict the output first, then look.
1def count_items(orders):2 counts = {}3 for item in orders:4 counts[item] = counts.get(item, 0) + 15 return counts67orders = ["latte", "tea", "latte"]8print(count_items(orders))
{'latte': 2, 'tea': 1}Faded lines didn't run with this value. The function does not know which products will come, yet it counts correctly in every list: the keys are created from the data. In the empty list, line 4 never runs, and the dictionary stays empty.
So why such a long line? Isn't counts[item] += 1 shorter? It is shorter but wrong. += first reads the current value, and then adds to it. When the first tea arrives, the key 'tea' is not in the dictionary; there is no value to read. get, on the other hand, does not raise an error when the key is missing; it returns the default you gave (0). Predict without running:
What does this code print?
order = ["tea", "latte", "tea"] counts = {} for item in order: counts[item] += 1 print(counts)
Now Ada asks about the money side: how much did each product earn? You use the same line, and the only difference is the number that is added. When counting, you added + 1 on every order; when totaling, you add the amount of that order. You read the amount from the menu: menu[item].
Example 3 (case): Revenue per product
menu = {"latte": 4.25, "cookie": 2.00, "tea": 1.25}
orders = ["latte", "tea", "latte", "cookie"]
revenue = {}
for item in orders:
revenue[item] = revenue.get(item, 0) + menu[item]
print(revenue)
print("Day revenue:", sum(revenue.values()))Output{'latte': 8.5, 'tea': 1.25, 'cookie': 2.0}
Day revenue: 11.75The first latte puts 4.25 into the slot, and the second latte takes this 4.25 with get and adds 4.25 on top: 8.5. When the loop ends, sum(revenue.values()) adds up the revenue of all products and gives the revenue of the day.
These two dictionaries say different things. The count dictionary tells you how many of a product were sold, not how much it earned. The best-selling product may not be the product that earned the most: four teas ($5.00) earn less than two lattes ($8.50). To say "tea earned the most money" from a count result, you also need the price information.
The counting pattern is not specific to the café. Counting the answers in a survey, the letters in a text, or the votes in an election is always done with the same line. Think of a class representative election: every ballot has a name written on it, and the names that come out of the box are in a list.
Example 4 (outside the case): Class representative election
votes = ["Emma", "Leo", "Emma", "Dana", "Emma", "Leo"] tally = {} for name in votes: tally[name] = tally.get(name, 0) + 1 for name, count in tally.items(): print(f"{name}: {count}")
OutputEmma: 3
Leo: 2
Dana: 1Finding the winner after counting is not a new concept: you use the "largest" pattern from lesson 12 with items(). You keep the candidate with the most votes so far in a variable, and compare each candidate's votes with theirs. Your turn: first run the code below as it is, then do the two tasks in the comments.
Try it now· not graded; doesn't affect progress
Ada's stock dictionary also holds products that have run out, and she wants to remove them. The first idea that comes to mind is to delete the key whose count is 0 while looping through the dictionary. But Python does not allow this: adding a key to the dictionary you are looping through, or deleting a key from it, raises RuntimeError: dictionary changed size during iteration. The message says exactly what happened: the size of the dictionary changed during the loop. The loop keeps track of which key it is at by looking at the structure of the dictionary; when the structure changes, it loses its place and stops.
Example 5 (case): Removing the sold-out items
The faulty way:
stock = {"latte": 0, "tea": 4, "water": 0}
for item in stock:
if stock[item] == 0:
del stock[item]Error:
OutputRuntimeError: dictionary changed size during iterationIf you added print(stock) to the end of the faulty code above, what would you see?
stock = {"latte": 0, "tea": 4, "water": 0}
for item in stock:
if stock[item] == 0:
del stock[item]
print(stock)The solution is simple: do not touch the dictionary you are looping through, and collect the result in a new dictionary. You read the old dictionary and write the entries that should stay into the new one. There is one more benefit: the original data stays intact. The "protect the original data" idea from lesson 25 applies here too.
stock = {"latte": 0, "tea": 4, "water": 0}
remaining = {}
for item, count in stock.items():
if count > 0:
remaining[item] = count
print(remaining)
print(stock)Output{'tea': 4}
{'latte': 0, 'tea': 4, 'water': 0}The same idea works for a price increase. If you want a new menu with $0.50 added to every product, instead of changing the old one you open an empty dictionary named new_menu and add each product with its new price:
menu = {"latte": 4.25, "tea": 1.25}
new_menu = {}
for item, price in menu.items():
new_menu[item] = price + 0.50
print(new_menu)
print(menu)Output{'latte': 4.75, 'tea': 1.75}
{'latte': 4.25, 'tea': 1.25}Know the limit of the rule well: what is forbidden is adding or deleting a key. Updating the value of an existing key does not change the size, so it is allowed; for item in menu: menu[item] += 0.25 runs without a problem. The update method, which merges two dictionaries, also adds keys to the dictionary; use it after the loop is finished too.
Now let's put the pieces together. We give the counting job to the count_items function and the job of finding the top seller to the top_item function. Separate functions apply the "split into parts" idea from lesson 16: each one does a single job and can be tested on its own. We align the output with the field width from lesson 22: :<6 pushes the product name to the left in a field of 6 characters, and :>3 pushes the count to the right in a field of 3 characters.
Example 6 (case): The target program of the lesson
def count_items(orders): # 1. Empty tally counts = {} # 2. Increase by one for each order for item in orders: counts[item] = counts.get(item, 0) + 1 return counts def top_item(counts): # 3. Find the key with the largest value top = "" for item, count in counts.items(): if top == "" or count > counts[top]: top = item return top day = ["latte", "tea", "latte", "water", "latte", "tea"] counts = count_items(day) for item, count in counts.items(): print(f"{item:<6}{count:>3}") print("Top seller:", top_item(counts))
Outputlatte 3
tea 2
water 1
Top seller: lattetop_item starts with an empty string; on the first product, top == "" is true, so latte is chosen. The count of the following products is not greater than 3, so the choice does not change. Because the comparison uses >, the first product seen stays when there is a tie. If the dictionary is empty, the loop never runs and the function returns an empty string.
Now build the count_items function yourself. The indentation matters as much as the order of the lines.
Put the lines of the count_items 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
Counting is such a common job that Python's standard library even has a tool that does it in one line: Counter. You will see it in lesson 37; behind the scenes, it keeps exactly the tally you built in this lesson.
The counting and totaling patterns can work together in the same loop. In the example below, tea is the best-selling product, but latte earns the most revenue: the count dictionary alone could not tell you this.
menu = {"latte": 4.25, "cookie": 2.00, "tea": 1.25}
orders = ["tea", "tea", "latte", "tea", "cookie", "tea", "latte"]
counts = {}
revenue = {}
for item in orders:
counts[item] = counts.get(item, 0) + 1
revenue[item] = revenue.get(item, 0) + menu[item]
for item in counts:
print(f"{item:<8}{counts[item]:>2} sold ${revenue[item]:.2f}")Outputtea 4 sold $5.00
latte 2 sold $8.50
cookie 1 sold $2.00The keys of the two dictionaries are the same, because both were filled from the same list in the same order. That is why we could loop through counts and read each product's revenue with revenue[item].
A class was asked "Should we go on the school trip?"; the answers arrived as a single string, and the letter case is mixed. We clean the string and split it into words with lower and split
Trying to get the key and the value together without writing `items()`. If you want to print the menu with product and price but forget items(), Python stops:
menu = {"tea": 1.25, "latte": 4.25}
for item, price in menu:
print(item, price)Error:
OutputValueError: too many values to unpack (expected 2)Read the message: "too many values to unpack, 2 were expected". Looping through a dictionary directly gives the keys; the thing that arrives on the first turn is the string "tea". Python tries to split this string into two boxes named item and price, but the string has three letters: three values do not fit into two boxes. The correct version is: for item, price in menu.items():. This way, a two-part pair arrives on each turn and fits exactly into the two names.
values() for the values and items() for the key and value together; sum(d.values()) adds up the values, and sorted(d) returns a sorted list of keys.d[k] = d.get(k, 0) + 1 for each element; if you write + amount instead of + 1, the same line totals. d[k] += 1 raises a KeyError on the first key it sees; finding the most frequent item is the "largest" pattern from lesson 12 used with items().RuntimeError, while updating a value is allowed; if you need to add or delete, collect the result in a new dictionary.Next lesson: An order has not only a product name but also a table, a quantity, and a payment type; we will keep each order as a dictionary, collect these dictionaries in a list, and group them.
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.
:.0%answers = "yes no yes Yes maybe no YES" tally = {} for answer in answers.lower().split(): tally[answer] = tally.get(answer, 0) + 1 total = sum(tally.values()) for answer, count in tally.items(): print(f"{answer:<6}{count:>2} {count / total:.0%}")
Outputyes 4 57%
no 2 29%
maybe 1 14%Without lower, yes, Yes, and YES would be three separate keys: dictionary keys are case sensitive. We found the total number of answers not with a separate counter but with sum(tally.values()).