MediumDictionariesNot started

Merge visitor counts

Two check-in desks export visitor-name counts. Merge both exports by adding counts for repeated names and print the combined counts alphabetically. A visitor appearing at only one desk must still appear. Never replace the first desk's count with the second desk's count.

Input

First line A, then A name count rows; next line B, then B more rows. Names are lowercase single tokens.

Output

Alphabetically sorted name total lines.

Example 1

Input

2
ana 2
ben 1
2
ana 3
cy 4

Output

ana 5
ben 1
cy 4

Ana appears at both desks and totals 5; Ben and Cy each appear at only one desk but remain in the alphabetical report.

Constraints

  • Each desk provides 0 to 200 rows.
  • Visitor counts are non-negative integers; repeated names may occur within either block.

Hints

Hint 1 of 2

Read two blocks with the same inner loop.

Hint 2 of 2

Use get(name, 0) so visitors missing from the first block are handled.

Solution

Show a reference solution and explanation
 Python · reference solution
totals = {}
for _ in range(2):
    count = int(input())
    for _ in range(count):
        name, visits = input().split()
        totals[name] = totals.get(name, 0) + int(visits)
for name in sorted(totals):
    print(name, totals[name])

Why it works

Both desks use the same counting rule, so one loop can process each block. Accumulation preserves repeated names within a block as well as across blocks. A final alphabetical sort makes the combined report independent of source ordering.

Lesson for this exercise: Dictionaries in Python

Your program
totals = {}
for _ in range(2):
    count = int(input())
    for _ in range(count):
        name, visits = input().split()
        # Add this row to the existing visitor total.
        pass
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.

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.