The Field Counter

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
Asked in
eHealth

Problem

Given a list of dicts (records) and a key name, return a dict mapping each distinct value found at that key to the number of records containing that value. Records that do not have the key must be skipped.

Some fields speak louder than others.

Example

Input:

records = [{"id":1,"dept":"eng"},{"id":2,"dept":"sales"},{"id":3,"dept":"eng"}], key = "dept"

Output:

{"eng":2,"sales":1}

Worked solution and explanation

Why this problem exists in real interviews

Counting occurrences in a stream of records is the most common shape of data work. Interviewers use this prompt to check whether you skip records that lack the key (instead of letting KeyError blow up), whether you reach for dict.get or defaultdict or Counter, and whether your output type matches what the harness expects.


Break down the requirements

Step 1: Skip records that lack the key

The spec says 'records that do not have the key must be skipped.' Use if key in r: (or wrap in try/except KeyError) before reading the value. Indexing blindly with r[key] will crash on the first missing record.

Step 2: Tally with dict.get or defaultdict(int)

counts[v] = counts.get(v, 0) + 1 works without an import. collections.defaultdict(int) and collections.Counter are both fine; just remember the harness expects a plain dict back, so cast if needed.

Step 3: Return the counts dict directly

Keys are the distinct values found at key; values are the integer counts. No sorting is required. Do not return a list of tuples or a Counter object if the harness compares against dict.


The solution

Linear scan with key-presence guard
def count_key_occurrences(records, key):
    counts = {}
    for r in records:
        if key in r:
            v = r[key]
            counts[v] = counts.get(v, 0) + 1
    return counts

Common follow-up questions