1. Lighthouse

Level 6 · Stock left after a day of sales

The request

From Debra Marshall, Warehouse Manager

“Here's this morning's stock count and today's sales as they came off the packing line. What do we have left on the shelf tonight, per product?”

Your goal

Set result to a dictionary with the same keys as stock, where each value is the morning stock minus every quantity sold for that product in sales (ints). Do not change the starting numbers by hand.

  • Store a dict in resultnot done yet

Your code

Python

Loading the editor…

    ResultPress Run to see yours

    Mote checks your result

    Press Run. Each row that matches the goal becomes a firefly in your lantern.

    The lesson

    Unpacking pairs in a loop

    Each sale is a tuple, a fixed pair of values: the product name and the quantity. When every item in a list has the same shape, you can unpack it straight in the for line:

    for name, qty in sales:
        print(name, qty)
    # Hazel Linen Throw Pillow 6
    # Northfield Brass Bud Vase 2
    # ...

    That is clearer than sale[0] and sale[1], and Python raises an error if a row ever has the wrong number of values, which is a useful early warning on a messy feed.

    Updating a dictionary in place

    A dictionary of stock levels is a running balance. Each sale reads the current number for that key and writes back the new one:

    left = dict(stock)                 # a copy, so the morning count stays intact
    left["Hazel Linen Throw Pillow"] = left["Hazel Linen Throw Pillow"] - 6    # 34

    The pillow appears three times in today’s sales: 6, 3 and 2 units. Each pass through the loop subtracts from what the previous pass left, so it goes 40, 34, 31, 29. The same line can be written with the shorthand left[name] -= qty.

    dict(stock) makes a new dictionary with the same keys and values. Working on a copy means you still have the morning numbers if someone asks “what did we start with?”, and you can rerun the calculation without reloading anything. If you wrote left = stock, both names would point at the same dictionary and the morning count would be overwritten.

    Check the totals

    A quick reconciliation catches most mistakes. The morning stock adds up to 85 units, and the sales add up to 23. Whatever you end with must add up to 85 - 23 = 62:

    sum(left.values())       # 62

    If your numbers don’t reconcile, a sale was skipped or counted twice.

    Common mistakes

    • Subtracting from the morning number on every pass (stock[name] - qty). Only the last sale of each product survives.
    • Writing left = stock instead of a copy, and then wondering why the morning count changed.
    • Forgetting that a product name in sales must match the key exactly. “Hazel linen throw pillow” with a lowercase l would raise a KeyError.

    Pick what may run on this site. You can change this any time from "Cookie settings" at the bottom of every page.