MediumDictionariesNot started

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

Your program
n = int(input())
totals = {}
for _ in range(n):
    sku, delta = input().split()
    # Add this movement to the SKU's existing total.
    pass
for sku in sorted(totals):
    print(sku, totals[sku])

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

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.