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
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 countsCommon follow-up questions
- How would you change the function to count by multiple keys at once and return a nested dict? (Tests structure design. The candidate should propose `{key_name: {value: count}}` and a single pass that updates all keys per record.)
- What if records are coming from a generator that may yield millions of items? Would you change anything? (Tests memory awareness. The function already streams since it iterates `records` once. The main risk is the output dict growing unbounded if cardinality is high.)
- How would you also return the most common value and its count? (Tests post-processing. `max(counts.items(), key=lambda kv: kv[1])` is the natural answer; `Counter.most_common(1)` is the idiomatic one if they used `Counter`.)