GroupBy Aggregation: Sum and Count per Key

PYTHON coding challenge · Difficulty: medium · Topic: Dictionary and Counter · +100 XP

Given two lists, keys and values, of equal length, compute for each unique key the total sum of its associated values and the count of occurrences. Return a dictionary mapping each key to a tuple (sum, count), with keys in the order they first appear in keys. Use plain Python (a dict); this is the same aggregation a SQL GROUP BY with SUM and COUNT performs.

Example Input

`

keys = [1, 2, 1, 3, 2, 1]

values = [10, 20, 30, 40, 50, 60]

`

Expected Output

`

{1: (100, 3), 2: (70, 2), 3: (40, 1)}

`

What this PYTHON challenge teaches you

“GroupBy Aggregation: Sum and Count per Key” is a medium-level PYTHON challenge focused on Dictionary and Counter. Working through it gives you hands-on practice with dictionary, groupby, aggregation — the kind of transformation you are asked to write in real data engineering work and in technical interviews. You can solve it directly in the browser: the dataset is pre-loaded, so you write the query or DataFrame code, run it, and compare your output against the expected result immediately.

Concepts covered

How to approach it

If you get stuck, work through these steps in order before looking at a full solution — each one narrows the problem down:

  1. 1 ≤ len(keys) ≤ 100,000
  2. len(keys) == len(values)
  3. -10^9 ≤ values[i] ≤ 10^9
  4. keys[i] are integers

How to practise it on PySpark.in

Open the challenge, write your Python code in the editor and press Run to execute it against the sample dataset. Submitting checks your output against every test case, including hidden ones, so you find out straight away whether your logic holds up. You can retry as often as you like, and each solved challenge adds to your XP.

Related PYTHON challenges

Helpful resources

Frequently asked questions

Do I need to install Spark or a database to solve this?

No. The PYTHON environment runs in your browser with the sample data already loaded, so there is nothing to install or configure.

Is this challenge free?

Yes - the problem, the sample dataset, the hints and unlimited test runs are free.

What level is it?

It is rated medium and covers Dictionary and Counter.

Solve this challenge free on PySpark.in