Inventory movement tally
A workshop records stock movements as product name and signed quantity. Read all movements, total the quantity for each product, and print products alphabetically as name total, including products whose final total is zero.
Input
First line N. Next N lines: a lowercase product name and a signed integer quantity.
Output
One line per product in alphabetical order: name, one space, final total.
Example 1
Input
5 bolts 8 nuts 4 bolts -3 washers 2 nuts -4
Output
bolts 5 nuts 0 washers 2
Movements for the same name are added before sorting.
Constraints
- 1 <= N <= 200
- -1000 <= quantity <= 1000
Hints
Hint 1 of 3
Use each product name as a dictionary key.
Hint 2 of 3
dict.get(name, 0) supplies a zero for a new product.
Hint 3 of 3
Iterate over sorted(totals) to control output order.
Solution
Show a reference solution and explanation
count = int(input())
totals = {}
for _ in range(count):
name, amount = input().split()
totals[name] = totals.get(name, 0) + int(amount)
for name in sorted(totals):
print(name, totals[name])
Why it works
The dictionary stores one running total per product. get handles the first movement without a separate branch, and sorting the keys at output time keeps accumulation independent from presentation order.
Lesson for this exercise: Dictionaries in Python