Use a dictionary to accumulate totals per category while looping over parallel lists, then list the categories sorted by name.
You start with:
items = ["Apple", "Bread", "Shirt", "Banana", "Pants"]
prices = [2, 3, 25, 1, 40]
categories = ["Food", "Food", "Clothes", "Food", "Clothes"]
Build:
Clothes: $65 Food: $6
Rules:
- Build a dictionary
totalsthat maps each category to the sum of the prices of its items. - Loop with an index. For each item, add its price to the total of
categories[i]; a category you have not seen yet counts as 0. - Make one line per category, in the format
"Category: $total", sorted alphabetically by category name (soClothescomes beforeFood). - Join the lines with a newline
"\n"into one stringresult. Just store the text inresult; you do not need to print it.
Use
totals.get(cat, 0) + prices[i] to accumulate without checking for missing keys.
Iterate the sorted keys with
for cat in sorted(totals):.
items = ["Apple", "Bread", "Shirt", "Banana", "Pants"]
prices = [2, 3, 25, 1, 40]
categories = ["Food", "Food", "Clothes", "Food", "Clothes"]
totals = {}
for i in range(len(items)):
cat = categories[i]
totals[cat] = totals.get(cat, 0) + prices[i]
lines = []
for cat in sorted(totals):
lines.append(cat + ": $" + str(totals[cat]))
result = "\n".join(lines)
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
