pandas: Total per group

Model df.groupby("key")["value"].sum(), the classic grouped total.

What to build

A program that totals values per key.

Requirements

  • Print KEY: TOTAL for each key in sorted order, then groups: G.

Input

Line 1: n. Then n lines KEY VALUE.

Output

One line per key, then the number of groups.

Constraints

1 ≤ n ≤ 1000; values are whole numbers.

Example

Input:

5
Dhaka 30
Paris 50
Dhaka 20
Lima 10
Paris 25

Output:

Dhaka: 50
Lima: 10
Paris: 75
groups: 3

Why it works

Splitting by key and adding within each group is exactly split, apply and combine, and the sorted keys match groupby's default order.

Examples

Example 1 · Input
5
Dhaka 30
Paris 50
Dhaka 20
Lima 10
Paris 25
Expected output
Dhaka: 50
Lima: 10
Paris: 75
groups: 3
Example 2 · Input
1
x 7
Expected output
x: 7
groups: 1

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

Hints

Hint 1

Add each amount to its key's running total in a dictionary.

Hint 2

Print the keys in sorted order, as groupby does.

Solution

Show one correct solution (try it yourself first)
n = int(input())
totals = {}
for _ in range(n):
    key, value = input().split()
    totals[key] = totals.get(key, 0) + int(value)
for key in sorted(totals):
    print(f"{key}: {totals[key]}")
print(f"groups: {len(totals)}")

Lesson: groupby: split, apply, combine →