Group Average

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L4

Problem

Metric readings arrive in data as [name, value] pairs, and the same name can repeat any number of times within a batch. The result maps each name to the average of every value recorded under it.

Same group, different values. What is typical?

Example 1

Input:

data = [["a",10],["b",20],["a",30]]

Output:

{"a":20,"b":20}

Example 2

Input:

data = [["x",100]]

Output:

{"x":100}

Worked solution and explanation

What this really is

This is a grouped mean dressed up as a dictionary exercise, and the only thing it grades is whether your divisor belongs to the key. Anyone can build a dict from pairs. The trap is treating each pair as the value for its name: dict(data) or result[key] = value keeps the last write, so the first example returns 30 for 'a' instead of 20.0. Worse, that version passes every input where each name appears once, so the bug ships quietly.

Step 1: Keep two numbers per key

A mean needs a total and a count, and both have to be scoped to the same key. One accumulator is not enough. Dividing by len(data) mixes every name's readings into a single divisor, and storing only the latest value throws the earlier readings away.

Step 2: Divide once, after the last pair

A key's count is final only when the input is exhausted. Walk the keys in sums and divide by counts[key]. An empty input never creates a key, so the result is an empty dict with no special case.

Accumulate per key, then divide
def group_averages(data):
    sums = {}
    counts = {}
    for pair in data:
        key = pair[0]
        value = pair[1]
        if key not in sums:
            sums[key] = 0
            counts[key] = 0
        sums[key] += value
        counts[key] += 1
    result = {}
    for key in sums:
        result[key] = sums[key] / counts[key]
    return result
Last write wins
result[key] = value for each pair. For the first example, 'a' ends at 30, and a test with only single readings never notices.
Sum and count per key
sums[key] += value and counts[key] += 1, then sums[key] / counts[key]. 'a' gets (10 + 30) / 2 = 20.0.

Common follow-up questions