Merge Inventories
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?
{"a": 1, "b": 5}{"a": 1, "b": 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?
Counter({"a": 0})- Nothing: the entry is dropped
- 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.)
VISIBLE = 3
CASES = [
(({'a': 1, 'b': 2}, {'b': 3, 'c': 4}), {'a': 1, 'b': 5, 'c': 4}, 'an item in both'),
(({}, {}), {}, 'both empty'),
(({'x': 0}, {'y': 1}), {'x': 0, 'y': 1}, 'a zero is kept'),
(({'a': 5}, {'a': -5}), {'a': 0}, 'a total of zero is kept'),
(({'a': -2}, {'b': 1}), {'a': -2, 'b': 1}, 'an owed item is kept'),
('a = {"k": 1}\nb = {"k": 2}\nmerge_inventories(a, b)\nresult = (a, b)', ({'k': 1}, {'k': 2}), 'the inputs are not changed'),
('a = {"k": 1}\nr = merge_inventories(a, {})\nresult = (r == a, r is a)', (True, False), 'the result is a new dictionary'),
]