Aggregate raw records into one number per category, the first step before any bar chart.
What to build
A program that sums values per category and lists the totals.
Requirements
- Sum the values of each category and print
CATEGORY: TOTAL, largest total first, equal totals in alphabetical order, totals written with:g.
Input
Line 1: n. Then n lines CATEGORY VALUE.
Output
One line per category.
Constraints
1 ≤ n ≤ 1000; categories are single words.
Example
Input:
5
Books 12.5
Toys 30
Books 7.5
Garden 45
Toys 10
Output:
Garden: 45
Toys: 40
Books: 20
Why it works
Grouping turns many records into one value per category, and sorting by the total makes the ranking the chart will show visible at once.
Examples
Example 1 · Input
5 Books 12.5 Toys 30 Books 7.5 Garden 45 Toys 10
Expected output
Garden: 45 Toys: 40 Books: 20
Example 2 · Input
3 b 1 a 1 c 2
Expected output
c: 2 a: 1 b: 1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
A dictionary from category to running total does the grouping.
Hint 2
Sort with the key (-total, name).
Solution
Show one correct solution (try it yourself first)
n = int(input())
totals = {}
for _ in range(n):
category, value = input().split()
totals[category] = totals.get(category, 0) + float(value)
for category, total in sorted(totals.items(), key=lambda kv: (-kv[1], kv[0])):
print(f"{category}: {total:g}")