Data science: Summarise salaries by department

Summarise a numeric column for each group, and compare the groups.

What to build

A program that summarises salaries per department.

Requirements

  • For each department print DEPT: n N, mean M, min A, max B, with the mean to two decimals, ordered by mean from highest and equal means alphabetically.
  • Then print overall mean: X over all rows, to two decimals.

Input

Line 1: n. Then n lines DEPT SALARY (whole numbers).

Output

One line per department, then the overall mean.

Constraints

1 ≤ n ≤ 10000.

Example

Input:

5
sales 300
it 500
sales 400
hr 350
it 700

Output:

it: n 2, mean 600.00, min 500, max 700
hr: n 1, mean 350.00, min 350, max 350
sales: n 2, mean 350.00, min 300, max 400
overall mean: 450.00

Why it works

Keeping each group's values lets every aggregate be computed from the same list, and the overall mean computed from the rows weights each department by its size, which an average of averages would not.

Examples

Example 1 · Input
5
sales 300
it 500
sales 400
hr 350
it 700
Expected output
it: n 2, mean 600.00, min 500, max 700
hr: n 1, mean 350.00, min 350, max 350
sales: n 2, mean 350.00, min 300, max 400
overall mean: 450.00
Example 2 · Input
1
x 10
Expected output
x: n 1, mean 10.00, min 10, max 10
overall mean: 10.00

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

Hints

Hint 1

Collect each department's salaries in a list: groups.setdefault(dept, []).append(salary).

Hint 2

The overall mean comes from all the rows, not from the departments' means.

Solution

Show one correct solution (try it yourself first)
n = int(input())
groups = {}
everything = []
for _ in range(n):
    dept, salary = input().split()
    groups.setdefault(dept, []).append(int(salary))
    everything.append(int(salary))

summary = [(dept, sum(v) / len(v), v) for dept, v in groups.items()]
for dept, mean, v in sorted(summary, key=lambda s: (-s[1], s[0])):
    print(f"{dept}: n {len(v)}, mean {mean:.2f}, min {min(v)}, max {max(v)}")
print(f"overall mean: {sum(everything) / n:.2f}")

Lesson: Grouping and aggregation →