TutreNews Learn

Tuples, copies and choosing the right structure

Putting it together: inventory and word statistics

Goal: Combine lists, dictionaries, sets and tuples to solve a small data task · 12 min

Real programs combine all four structures. Here is the way an experienced programmer thinks about a data task.

Task: from a list of orders (item, quantity) compute the total per item, report the best seller, and list the items that were ordered only once.

Step 1 — choose structures. Orders are an ordered list of tuples (item, qty). Totals per item → a dictionary item → total. "Ordered only once" needs a count per item → another dictionary or Counter. Unique items → a set.

Step 2 — write the loop.

orders = [("tea", 2), ("cake", 1), ("tea", 3), ("milk", 1)]
totals = {}
times = {}
for item, qty in orders:
    totals[item] = totals.get(item, 0) + qty
    times[item] = times.get(item, 0) + 1
best = max(totals, key=totals.get)
once = sorted(i for i, t in times.items() if t == 1)
print(totals)   # {'tea': 5, 'cake': 1, 'milk': 1}
print(best)     # tea
print(once)     # ['cake', 'milk']

Step 3 — test with small data, including edge cases: an empty list (what should max do? It raises ValueError, so guard with if orders:), a single order, equal totals.

Step 4 — name things clearly (totals, times), keep functions small, and write down the result structure you return.

Typical bugs to look for: KeyError (missing .get), modifying a list while looping over it, sharing a mutable default, forgetting that sorted on a dictionary returns only keys.

Worked example: Best seller

  1. Totals: tea 5, cake 1, milk 1.
  2. max(totals, key=totals.get) returns the key with the largest value: "tea".
  3. Items ordered once: those whose order count is 1.
orders = [("tea", 2), ("cake", 1), ("tea", 3), ("milk", 1)]
totals = {}
for item, qty in orders:
    totals[item] = totals.get(item, 0) + qty
print(totals)
print(max(totals, key=totals.get))

Output:

{'tea': 5, 'cake': 1, 'milk': 1}
tea