Stock movement ledger
A warehouse exports N movement records, each with a SKU and a signed integer change. Sum every SKU's changes, including zero totals, and print one SKU total line per SKU in alphabetical order. Never replace an earlier movement with a later one.
Input
First line N; then N lines containing a SKU and signed integer delta.
Output
Sorted SKU total lines, one for each distinct SKU.
Example 1
Input
5 tea 4 rice -2 tea -1 flour 0 rice 5
Output
flour 0 rice 3 tea 3
Tea's two changes combine to 3, rice ends at 3 after a negative movement, and flour stays visible at zero; IDs print alphabetically.
Constraints
- 1 <= N <= 200 movement rows.
- SKU is a non-empty lowercase token; each signed delta is between -100000 and 100000.
Hints
Hint 1 of 2
Use a dictionary whose key is the SKU.
Hint 2 of 2
Keep a zero total in the dictionary; it is still a recorded SKU.
Solution
Show a reference solution and explanation
n = int(input())
totals = {}
for _ in range(n):
sku, delta = input().split()
totals[sku] = totals.get(sku, 0) + int(delta)
for sku in sorted(totals):
print(sku, totals[sku])
Why it works
Accumulate each signed delta with get(sku, 0) so repeated records add instead of overwrite. Sorting only at output makes the report independent of arrival order. A zero net change remains visible because that SKU did have movements.
Lesson for this exercise: Dictionaries in Python