Medium: Interview Core · Problem 36 of 82

Merge Inventories

MediumDictionaries and SetsPython

Two warehouses keep their stock as dictionaries from item name to quantity. Write merge_inventories(a, b) that returns a new dictionary with every item from either, where an item in both has its quantities added.

Keep items whose total is zero. Do not change a or b. Quantities may be zero or negative (a negative number is an order that is owed).

Understand the problem

Compare the merging tools.

What does {"a": 1, "b": 2} | {"b": 3} give?

  1. {"a": 1, "b": 5}
  2. {"a": 1, "b": 3}
  3. {"a": 1, "b": 2, "b": 3}

The | operator merges dictionaries, and when a key is in both, the right-hand value wins. It does not add. A dictionary cannot hold the same key twice.

What does Counter({"a": 1}) + Counter({"a": -1}) contain?

  1. Counter({"a": 0})
  2. Nothing: the entry is dropped
  3. An error

Adding Counters keeps only positive totals. An item whose total is zero or negative disappears. That is useful for counts, and wrong when you must keep zeros, as this task says.

Write the solution

Return a new dictionary and leave the inputs alone.

def merge_inventories(a, b):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

What should happen for an item that is only in a, only in b, or in both?

Hint 2: the shape of the answer

Start with a copy of a (dict(a)). For each (item, quantity) of b, add it to the copy, using get(item, 0) for items that are new.

Reflect

Solution

def merge_inventories(a, b):
    merged = dict(a)
    for item, quantity in b.items():
        merged[item] = merged.get(item, 0) + quantity
    return merged

Another way: loop over all the keys

def merge_inventories(a, b):
    return {item: a.get(item, 0) + b.get(item, 0) for item in a.keys() | b.keys()}

What this tests: dict(a) to copy, get with a default, dictionary views (a.keys() | b.keys() is the set of all keys), and not changing the inputs.

Counter is tempting but wrong here. Counter(a) + Counter(b) throws away entries whose total is zero or below. For stock with owed items or zero counts that loses data. (Counter.update and Counter.subtract keep zeros; + and - do not.)

Copy before changing: writing into a would change the caller's data. dict(a) makes a new dictionary first.

Cost: O(len(a) + len(b)).

What an interviewer might ask next: Merge any number of inventories. (functools.reduce(merge_inventories, inventories, {}), or one loop with the copy made once.)