Process a list of product dictionaries with a function and a loop, and print a short inventory report.
How it works
Reading values from a dictionary
Use the key in square brackets to get a value. Inside an f-string, a $ is just text, and the value goes in { }:
book = {"title": "Dune", "price": 12}
print(book["title"])
print(f"Cost: ${book['price']}")
Inside an f-string that uses double quotes, write the key with single quotes, like book['price']. That works in every Python version.
A function that takes a dictionary
def area(room):
return room["w"] * room["l"]
print(area({"w": 3, "l": 4}))
Gotcha: start the total before the loop
If total = 0 is inside the loop, it resets on every pass and only the last value survives:
items = [4, 6]
for n in items:
total = 0
total = total + n
print(total)
Your task
The starter code gives you products, a list of three dictionaries, each with a name, price and qty.
- Write
line_value(item) so it returns the item's price times its qty. - Loop over
products. For each one, get its value with line_value(product), print <name>: $<value>, and add the value to total. - After the loop, print
Total: $<total>.
f-strings make the printed lines easy. The checker also calls line_value on a different product and checks total, so don't type the numbers in.
Expected output
Keyboard: $120
Mouse: $200
Monitor: $300
Total: $620
Hint
Inside the loop, store line_value(product) in a variable first. Then use that variable twice: once in the print and once to grow total.