MediumDictionariesNot started

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
 Python · reference solution
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

Your program
count = int(input())
totals = {}
for _ in range(count):
    name, amount = input().split()
    # update totals
for name in sorted(totals):
    print(name, totals[name])

Tests: 3 cases including the examples. Passing every test marks the exercise solved in this browser.

Ready for a challenge?

How this page was checked. Every program on it was run with CPython 3.11 at build time; runs in your browser on CPython 3.14 (Pyodide) by the publishing checks, and the output shown is what it printed. The Run buttons execute the same code on your device; nothing you type is sent anywhere.