Compare Two Inventory Snapshots

Hard ⏱ 18 min 30% acceptance ★★★★★ 4.8
Write a function diff_inventory(old, new) comparing two stock dicts (product -> quantity). Return a dict with three keys: "added" (products in new but not old, mapped to their new quantity), "removed" (products in old but not new, mapped to their old quantity), and "changed" (products in both with different quantities, mapped to a tuple (old_qty, new_qty)).

Examples

Example 1
Input
diff_inventory({'pen': 10, 'bag': 5, 'mug': 2}, {'pen': 10, 'bag': 8, 'cup': 4})
Output
{'added': {'cup': 4}, 'removed': {'mug': 2}, 'changed': {'bag': (5, 8)}}
Explanation

pen unchanged so excluded everywhere; bag quantity changed; mug removed; cup added.

Constraints

  • Unchanged products appear in none of the three result dicts.

Topics

Dictionariescomparisonbusiness logic

Companies

WalmartFlipkart

Hints

Hint 1

Use set operations on `old.keys()` and `new.keys()` to find added/removed key sets.

Hint 2

For shared keys, compare quantities and collect the differing ones.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.