…
…
Python Programming Fundamentals · Lesson 28 / 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.
Corner Café no longer keeps just a product name for each order. It keeps four pieces of information: product, quantity, unit price, and payment type. When Ada counts the register at the end of the day, she asks: "How much came in by card, and how much in cash?" In this lesson you will keep the order records in a list, and write a function that groups them by payment type and by product and adds them up.
The program you will write by the end of the lesson will produce this summary from the day's five orders:
Outputcard $12.00
cash $8.00All the examples in this lesson use the same five orders. An order is no longer a single value, but a record made of several fields:
orders = [
{"product": "latte", "quantity": 2, "price": 4.25, "payment": "card"},
{"product": "tea", "quantity": 3, "price": 1.25, "payment": "cash"},
{"product": "cookie", "quantity": 1, "price": 2.00, "payment": "card"},
{"product": "latte", "quantity": 1, "price": 4.25, "payment": "cash"},
{"product": "water", "quantity": 2, "price": 0.75, "payment": "card"},
]The order amounts are $8.50, $3.75, $2.00, $4.25, and $1.50 in turn; the day's total is $20.00. Keep these numbers in mind. Throughout the lesson you will compare the outputs of your program with them.
In this lesson you will:
In lesson 26 you learned to keep one order in a dictionary: {"product": "latte", "quantity": 2}. In lesson 23 you learned to collect many values in a list. Real data needs both at once: dozens of orders arrive every day, and each order has several fields. The solution is to put dictionaries inside a list. A list in which every element is a dictionary with the same keys is called a record list.
You can think of a record list as a table: each dictionary is a row, and each key is a column. The row number is the position in the list.
| position | product | quantity | price | payment |
|---|---|---|---|---|
| 0 | latte | 2 | 4.25 | card |
| 1 | tea | 3 | 1.25 | cash |
| 2 | cookie | 1 | 2.00 | card |
| 3 | latte | 1 | 4.25 | cash |
| 4 | water | 2 | 0.75 | card |
You reach a value in two steps. First you select the record by position in the list, then you read the field with its key in that dictionary. orders[1] gives the second receipt, that is, a whole dictionary. orders[1]["product"] gives the product field of that receipt. The expression is read from left to right: each pair of square brackets applies to the result of what comes before it. Because orders[1] is a dictionary, you can write ["product"] after it.
Example 1 (case): One record, one field
orders = [
{"product": "latte", "quantity": 2, "price": 4.25, "payment": "card"},
{"product": "tea", "quantity": 3, "price": 1.25, "payment": "cash"},
{"product": "cookie", "quantity": 1, "price": 2.00, "payment": "card"},
{"product": "latte", "quantity": 1, "price": 4.25, "payment": "cash"},
{"product": "water", "quantity": 2, "price": 0.75, "payment": "card"},
]
print(orders[1])
print(orders[1]["product"])
print(orders[-1]["quantity"] * orders[-1]["price"])Output{'product': 'tea', 'quantity': 3, 'price': 1.25, 'payment': 'cash'}
tea
1.5The first line printed the whole dictionary, because we only selected the record. The second line printed a single value, because after the record we also selected the field. The third line uses a negative index: -1 selects the last record, the water order; the quantity (2) is multiplied by the price (0.75), and the result is 1.5 (Python does not print the trailing zero).
The same rule works in the other direction: a dictionary can contain a list. Let the table record hold the table number, the waiter, and the list of products that came to that table.
Example 2 (case): A list inside a dictionary
table = {"number": 3, "waiter": "Lena", "items": ["latte", "cookie"]}
print(table["items"][1])
print(len(table["items"]))Outputcookie
2This time the key comes first: table["items"] gives a list, then [1] selects the second element of that list. The rule is always the same: left to right, and at each step look at the type of what you are holding. If it is a list, you write a position number; if it is a dictionary, you write a key. Match each expression with its value below.
Using the case data and the table from Example 2, what is the value of each expression?
For each row, pick its match from the list, then check.
orders[0]["product"]orders[2]["price"]orders[-1]["payment"]orders[1]table["items"][0]orders["product"]Now a prediction with names from outside the case. Answer without running the code.
What does this code print?
records = [{"name": "latte", "quantity": 2}, {"name": "tea", "quantity": 3}]
print(records[1]["quantity"] + records[0]["quantity"])Writing position numbers one by one is rarely useful in a record list; on a day with fifty orders, nobody writes orders[37]. Record lists are almost always processed with a for loop. When you write for r in orders:, r becomes a dictionary on each turn, that is, one receipt. You reach its fields with r["quantity"] and r["payment"]. There is no new pattern here: you apply the accumulation and filtering patterns from lesson 12 to a list whose elements are dictionaries.
The code below accumulates the revenue of the first three orders. Watch step by step, and pay attention to two things: the o box holds a whole dictionary on each turn, and revenue grows as 8.5, 12.25, and 14.25. Then use "Change the code" to delete [:3] and try all five orders; the result should be 20.0.
Run the code line by line: see which line runs next, the variable boxes and the output.
orders = [
{"product": "latte", "quantity": 2, "price": 4.25, "payment": "card"},
{"product": "tea", "quantity": 3, "price": 1.25, "payment": "cash"},
{"product": "cookie", "quantity": 1, "price": 2.00, "payment": "card"},
{"product": "latte", "quantity": 1, "price": 4.25, "payment": "cash"},
{"product": "water", "quantity": 2, "price": 0.75, "payment": "card"},
]
revenue = 0
for o in orders[:3]:
revenue += o["quantity"] * o["price"]
print(revenue)To select by a condition, you add an if inside the loop. Let's write the question "Which products were bought by card?" as a function, so that tomorrow you can call it with another day's list too. The function takes the record list as a parameter, collects the product names it selects in a new list, and returns it.
Example 3 (case): Products of the card orders
orders = [
{"product": "latte", "quantity": 2, "price": 4.25, "payment": "card"},
{"product": "tea", "quantity": 3, "price": 1.25, "payment": "cash"},
{"product": "cookie", "quantity": 1, "price": 2.00, "payment": "card"},
{"product": "latte", "quantity": 1, "price": 4.25, "payment": "cash"},
{"product": "water", "quantity": 2, "price": 0.75, "payment": "card"},
]
def card_products(records):
# 1. Open an empty list
selected = []
# 2. Add the product of each card record
for r in records:
if r["payment"] == "card":
selected.append(r["product"])
# 3. Return it
return selected
print(card_products(orders))Output['latte', 'cookie', 'water']The name orders never appears inside the function; the function works only with the records it is given. That is why you can call the same function with yesterday's list or another branch's list. r["payment"] == "card" looks at the payment field of the current receipt on each turn; if it is true, the product field of that receipt is added to the list.
Let's go back to Ada's question: "How much did each payment type bring in?" You could solve this with two separate loops, adding up card first and then cash. But if "transfer" shows up tomorrow, you would have to write a third loop; if revenue by product is wanted, four loops for four products. Instead, we will add up all the groups at once in a single loop.
The method is the same as the counter pattern in lesson 27. You start with an empty dictionary. In each record you use the value of the group field, for example r["payment"], as the key. Then you take the current total for that key with get(key, 0) and add the amount of the record on top. If the key is seen for the first time, get gives 0, so the compartment starts from zero. The only difference from the counter is this: there you added + 1 on each record, and here you add + amount.
If we make the group field a parameter, the same function answers every question: group_sum(orders, "payment") returns revenue by payment type, and group_sum(orders, "product") returns revenue by product.
Example 4 (case): The lesson's target program
orders = [
{"product": "latte", "quantity": 2, "price": 4.25, "payment": "card"},
{"product": "tea", "quantity": 3, "price": 1.25, "payment": "cash"},
{"product": "cookie", "quantity": 1, "price": 2.00, "payment": "card"},
{"product": "latte", "quantity": 1, "price": 4.25, "payment": "cash"},
{"product": "water", "quantity": 2, "price": 0.75, "payment": "card"},
]
def group_sum(records, field):
# 1. Empty drawer
totals = {}
# 2. Add the amount of each record to its own compartment
for r in records:
amount = r["quantity"] * r["price"]
totals[r[field]] = totals.get(r[field], 0) + amount
# 3. Return it
return totals
for payment, revenue in group_sum(orders, "payment").items():
(f)
(group_sum(orders, ))Outputcard $12.00
cash $8.00
{'latte': 12.75, 'tea': 3.75, 'cookie': 2.0, 'water': 1.5}In the first record, the value of r[field] is "card", and there is no card compartment in the drawer yet; get gives 0 and 8.5 is put in the compartment. In the second record the cash compartment is opened and 3.75 is put in. The third record is card again: this time get gives 8.5, and adding 2.0 makes 10.5. When the loop ends, card is 12.0 and cash is 8.0; their sum is 20.0, the day's revenue. The last line calls the same function with the product field: the two latte records (8.5 and 4.25) merge in a single compartment and make 12.75. The alignment in the output is from lesson 22: :<6 pushes the payment name left in a 6-character field, and :.2f shows the amount with two digits after the decimal point. Revenue by product looks like this on a chart:
$ · Corner Café sample data
| — | Revenue |
|---|---|
| Latte | 12.75 |
| Tea | 3.75 |
| Cookie | 2 |
| Water | 1.5 |
Now build the function yourself. The indentation matters as much as the order of the lines: pay attention to where the return line stands.
Put the lines of the group_sum 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
Many students think the group keys must be written in advance: totals = {"card": 0, "cash": 0}. It is not needed, and it is even harmful: when a new value shows up in the data, you will have forgotten that key. In the block below, change the value of field. Whichever field you choose, the keys are created from the data by themselves. Look especially at the last button: when you choose a field that is not in the records, Python does not give an empty value; it gives an error.
Which field are we grouping by? Change the value of field and look at the keys of the dictionary.
Pick a value; predict the output first, then look.
1orders = [2 {"product": "latte", "quantity": 2, "price": 4.25, "payment": "card"},3 {"product": "tea", "quantity": 3, "price": 1.25, "payment": "cash"},4 {"product": "cookie", "quantity": 1, "price": 2.00, "payment": "card"},5 {"product": "latte", "quantity": 1, "price": 4.25, "payment": "cash"},6 {"product": "water", "quantity": 2, "price": 0.75, "payment": "card"},7]8field = "payment"9totals = {}10for r in orders:11 amount = r["quantity"] * r["price"]12 totals[r[field]] = totals.get(r[field], 0) + amount13print(totals)
{'card': 12.0, 'cash': 8.0}Faded lines didn't run with this value. You never wrote the keys anywhere: the first time the field value of a record is seen, it is added to the dictionary by itself. Grouping by "price" also works, but the keys become numbers (4.25, 1.25, 2.0, 0.75). The "table" field, which is not in the records, gives KeyError: 'table' on the first record: Python does not make up an empty value for a missing key, it stops.
The most common mistake in grouping is overwriting instead of adding. The code below uses the same data, but the get part is missing. Predict without running it.
What does this code print?
orders = [
{"product": "latte", "quantity": 2, "price": 4.25, "payment": "card"},
{"product": "tea", "quantity": 3, "price": 1.25, "payment": "cash"},
{"product": "cookie", "quantity": 1, "price": 2.00, "payment": "card"},
{"product": "latte", "quantity": 1, "price": 4.25, "payment": "cash"},
{"product": "water", "quantity": 2, "price": 0.75, "payment": "card"},
]
totals = {}
for r in orders:
totals[r["product"]] = r["quantity"] * r["price"]
print(totals["latte"])Sometimes the question is not "how much?" but "which ones?" Ada wonders: "Which products were bought by card, and which by cash?" This time the value of each group must be a list, not a number. The pattern is still the cash drawer with compartments, but you put receipts in the compartments, not money.
The difference is in a single step. When adding up numbers, you could start a missing compartment from zero with get(key, 0). To append to a list, the list must exist first. So on each record you first ask: is this key in the drawer? If not, you open an empty list for it. Then, whether it was just opened or already there, you add the product of the record to that list.
key (payment) | value (product list) |
|---|---|
'card' | ['latte', 'cookie', 'water'] |
'cash' | ['tea', 'latte'] |
Example 5 (case): Product list by payment type
orders = [
{"product": "latte", "quantity": 2, "price": 4.25, "payment": "card"},
{"product": "tea", "quantity": 3, "price": 1.25, "payment": "cash"},
{"product": "cookie", "quantity": 1, "price": 2.00, "payment": "card"},
{"product": "latte", "quantity": 1, "price": 4.25, "payment": "cash"},
{"product": "water", "quantity": 2, "price": 0.75, "payment": "card"},
]
def group_by(records, field):
groups = {}
for r in records:
key = r[field]
if key not in groups:
groups[key] = []
groups[key].append(r["product"])
return groups
print(group_by(orders, "payment"))Output{'card': ['latte', 'cookie', 'water'], 'cash': ['tea', 'latte']}The products go into the list in the order they arrive: in the card list, latte is first and water is last. Notice that the append line is outside the if block, four spaces back; the addition is made on every record, whether the key is new or old. Later, in libraries that work with table data (for example pandas), this job is also called "grouping"; here you built with your own hands the logic of what is done there in a single line. Now let's see why the if lines are needed.
What happens if if key not in groups: and the line under it are deleted from the function in Example 5?
orders = [
{"product": "latte", "quantity": 2, "price": 4.25, "payment": "card"},
{"product": "tea", "quantity": 3, "price": 1.25, "payment": "cash"},
]
def group_by(records, field):
groups = {}
for r in records:
key = r[field]
groups[key].append(r["product"])
return groups
print(group_by(orders, "payment"))In earlier lessons we sometimes kept product names in one list and prices in a second list. In that arrangement, we could tell which price belonged to which product only from the position; forgetting to add to one list while adding an element to the other shifted the whole match. In a record list, each value stays together with its own field name: when you write r["price"], it is clear what you are reading, so the data explains itself. Adding a new field is also easy. Suppose that tomorrow a "table" field is added to each order; group_sum keeps working without any change, and group_sum(orders, "table") even gives the revenue by table. Later, when you read CSV and JSON files, you will see that the data arrives in exactly this form, as a list made of dictionaries; the patterns in this lesson will be directly useful to you at that point.
The same pattern works exactly the same outside the café. A library keeps the member, the book, and how many days late it was returned in each loan record. First we group and add up the total days late per member, then we write a fee of $0.50 per day for the members who have any late days.
loans = [
{"member": "Elena", "book": "Les Misérables", "days_late": 3},
{"member": "Marco", "book": "The Hobbit", "days_late": 0},
{"member": "Elena", "book": "Dune", "days_late": 5},
{"member": "Noah", "book": "Emma", "days_late": 2},
]
days_late = {}
for loan in loans:
days_late[loan["member"]] = days_late.get(loan["member"], 0) + loan["days_late"]
print(days_late)
for member, days in days_late.items():
if days > 0:
print(f"{member}: ${days * 0.50:.2f} fine")Output{'Elena': 8, 'Marco': 0, 'Noah': 2}
Elena: $4.00 fine
Noah: $1.00 fineReaching a record list like a dictionary. If you want to get the products of all the orders and write the key directly, Python stops:
print(orders["product"])
Error:
OutputTypeError: list indices must be integers or slices, not strThe message says exactly what the problem is: a list index must be an integer or a slice, it cannot be a string. orders is not a dictionary, but a list made of dictionaries; you need to select a record first. The right way: orders[0]["product"] for a single record, and for r in orders: with r["product"] inside the loop for all the records.
Misspelling the key name. If you write orders[0]["Product"], you get KeyError: 'Product'. Python does not make up an empty value; compare the name in the message with the name in the record letter by letter. Here the capital P causes the problem: in the record, the key is "product".
list[position][key], selecting the record first and the field second, and records are mostly walked through with for r in list:.totals[r[field]] = totals.get(r[field], 0) + amount on each record; the keys are created from the data by themselves, and = alone overwrites.groups[key] = [], then add the record with append; adding without opening the list gives a KeyError.Next lesson: Some records must never change, and in some lists we do not want repeats; you will learn the tuple and the set.
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.
The group field is "member", and the field being added up is "days_late". Elena's two records (3 and 5) become 8 in a single compartment. Marco's record also enters the dictionary, but because it is 0 days, it does not get a fine line.
Your turn. Run the code as it is first, then make the three changes in the comments one by one. For the third change, predict the output before running.
Try it now· not graded; doesn't affect progress