Merge Counters

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
L3

Problem

Given two warehouse feeds d1 and d2, each mapping a produce item name to its stock count, return one count per item. An item that appears in both feeds gets the sum of its two counts. Leave both feeds unchanged, because the analyst still reads them afterward.

Two tallies. Combine them.

Example 1

Input:

d1 = {"pears":2,"apples":4}, d2 = {"pears":3,"plums":6}

Output:

{"pears":5,"apples":4,"plums":6}

Example 2

Input:

d1 = {}, d2 = {}

Output:

{}

Worked solution and explanation

This is a key collision problem dressed up as warehouse bookkeeping. Every candidate knows how to put two dicts together. The real question is what happens when both feeds report the same item. Python's merge primitives ({**d1, **d2}, d1.update(d2), d1 | d2) all answer it with last write wins, so the first warehouse's count for every shared item silently disappears. Get that wrong and 'pears' comes back as 3 instead of 5, and nothing raises an error.

3 rules hiding in one sentence

Step 1: Copy d1 into a fresh dict

Start from a new result and copy every entry of d1 into it. That one decision settles two requirements at once. Items that only the first feed reports survive, and the analyst's d1 is never touched, because every later write lands on result.

Step 2: Fold in d2 with a membership check

For each item in d2, check whether result already holds it. If it does, add the count; if it does not, insert it. That check is what turns a merge into a sum. Without it you are back to update semantics.

Step 3: Let the empty case fall out

When both feeds are empty, both loops run zero times and result stays {}. No guard clause is needed, and adding one only gives a reviewer more to read.

Membership-checked merge into a fresh dict
def merge_dicts(d1, d2):
    result = {}
    for item in d1:
        result[item] = d1[item]
    for item in d2:
        if item in result:
            result[item] += d2[item]
        else:
            result[item] = d2[item]
    return result
Plain merge
{**d1, **d2} keeps every key but resolves 'pears' to the second feed's 3. Shared items are undercounted, while every test with no overlap still passes. That is how this bug ships.
Membership-checked sum
result[item] += d2[item] runs when the item is already present, and plain assignment runs otherwise. 'pears' becomes 5, and both inputs leave the call exactly as they arrived.

Common follow-up questions