pandas: Add two Series with alignment

Model what s1 + s2 and s1.add(s2, fill_value=0) do when the two Series have different labels.

What to build

A program that adds two Series by label, with and without a fill value.

Requirements

  • For every label in either Series, in alphabetical order, print LABEL: A | B where A is the result of s1 + s2 (NaN when the label is missing on either side) and B the result of s1.add(s2, fill_value=0).

Input

Line 1: n. Then n lines LABEL VALUE (the first Series). Next line: m. Then m lines (the second Series).

Output

One line per label.

Constraints

0 ≤ n, m ≤ 50; labels within one Series are distinct; values are whole numbers.

Example

Input:

3
apple 3
bread 2
milk 1
3
bread 1
milk 2
tea 4

Output:

apple: NaN | 3
bread: 3 | 3
milk: 3 | 3
tea: NaN | 4

Why it works

Alignment pairs values by label, so a label present on one side only has nothing to add to; fill_value supplies the missing partner as 0.

Examples

Example 1 · Input
3
apple 3
bread 2
milk 1
3
bread 1
milk 2
tea 4
Expected output
apple: NaN | 3
bread: 3 | 3
milk: 3 | 3
tea: NaN | 4
Example 2 · Input
1
x 5
1
x -5
Expected output
x: 0 | 0

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Walk the sorted union of both sets of labels.

Hint 2

For plain +, a label missing on either side gives NaN; with fill_value=0 the missing side counts as 0.

Solution

Show one correct solution (try it yourself first)
n = int(input())
s1 = {}
for _ in range(n):
    label, value = input().split()
    s1[label] = int(value)
m = int(input())
s2 = {}
for _ in range(m):
    label, value = input().split()
    s2[label] = int(value)
for label in sorted(set(s1) | set(s2)):
    plain = s1[label] + s2[label] if label in s1 and label in s2 else "NaN"
    filled = s1.get(label, 0) + s2.get(label, 0)
    print(f"{label}: {plain} | {filled}")

Lesson: Series: one labelled column →