Start learning free

LESSON 191 OF 673 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V6 in Python: Totals per Category with a Dictionary

Practice Read the full explanation

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 totals that 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 (so Clothes comes before Food).
  • Join the lines with a newline "\n" into one string result. Just store the text in result; 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)

STEP 1 OF 8
    Ctrl + Enter to check

    PYTHON · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V6 in Python, explained

    Problem overview

    Version 6 of the cart groups items by category. Three parallel lists describe the cart: items, prices and categories, where position i in each list describes the same item. The program adds up the prices within each category and stores one row per category in result, sorted alphabetically by category name.

    For the starting data, the clothes cost 25 + 40 and the food costs 2 + 3 + 1:

    Clothes: $65
    Food: $6

    The list order doesn't decide the row order: "Food" appears first in the data, but "Clothes" comes first in the output.

    Approach: accumulate in a dictionary, then sort the keys

    The categories aren't known in advance, so the program can't create one variable per category. A dictionary named totals fits: its keys are the category names that have appeared, and each value is the sum so far. The loop adds each item's price to its category's entry.

    A dictionary hands back its keys in the order they were first inserted, which is not alphabetical. The second half of the program therefore sorts the keys and builds one row for each, then joins the rows.

    Step by step

    1. Create the empty dictionary totals. It starts with no categories.
    2. Loop over positions. for i in range(len(items)) visits every item by its index, so the same i can read categories and prices.
    3. Read the category. cat = categories[i] names this item's group.
    4. Add the price. totals[cat] = totals.get(cat, 0) + prices[i]. For a category seen for the first time, get supplies 0, so the entry starts at the item's price.
    5. Create the empty list lines. This happens after the loop, so every total is final.
    6. Loop over the sorted keys. sorted(totals) returns the dictionary's keys as a list in alphabetical order.
    7. Append each category's row. The category, a colon, a space, a dollar sign and its total as text.
    8. Join the rows with a newline between each two.

    Here is how totals grows during the first loop, one pass per line:

    0 Apple Food {'Food': 2}
    1 Bread Food {'Food': 5}
    2 Shirt Clothes {'Food': 5, 'Clothes': 25}
    3 Banana Food {'Food': 6, 'Clothes': 25}
    4 Pants Clothes {'Food': 6, 'Clothes': 65}

    After the loop, sorted(totals) is ['Clothes', 'Food'].

    The solution in Python

    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)
    

    Details worth knowing:

    • The get default does the first-time work. Without it, totals[cat] would raise a KeyError for a category that has no entry yet. The default 0 means "nothing added so far", so no separate if cat in totals is needed.
    • Iterating a dictionary gives its keys. sorted(totals) is the same as sorted(totals.keys()). It returns a new list and leaves the dictionary untouched.
    • A dictionary can't be sorted in place. It remembers insertion order, so totals still lists Food before Clothes after the program runs. Only the list of keys is sorted.
    • Two loops, two jobs. The first collects, the second reports. Keeping them separate means the rows are written once per category, not once per item.
    • Strings are sorted by character code. That is alphabetical for names that start the same way, but not for mixed case.

    Edge cases and common mistakes

    • Uppercase sorts before lowercase. With categories ["food", "Toys", "Food"] and prices 1, 2 and 3, the rows are Food: $3, Toys: $2 and food: $1. Capitalisation also makes food and Food two different categories.
    • An empty cart. With empty lists the loop never runs, no rows are added and result is the empty string ''.
    • Replacing instead of adding. totals[cat] = prices[i] would keep only the last price of each category.
    • Using totals[cat] += prices[i] on a new key. It raises a KeyError the first time a category appears.
    • Appending rows inside the first loop. The program would write a row for every item with a partial total.
    • Forgetting str(). A total is an integer, so it has to be converted before it joins the text.

    Testing

    • The starting lists give Clothes: $65 and Food: $6.
    • ["A", "B", "C"], [1, 2, 3] and ["food", "Toys", "Food"] give Food: $3, Toys: $2 and food: $1.
    • Three empty lists give an empty result.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free