Problem overview
The function restock receives a dictionary inventory that maps item names to counts, an item that is always one of its keys, and an amount of at least 1. It adds amount to the count of item and returns the updated dictionary. Every other entry stays as it is.
For {"apples": 5, "bananas": 2, "cherries": 10}, item = "bananas" and amount = 3, the result is {'apples': 5, 'bananas': 5, 'cherries': 10}.
Approach
A dictionary entry can be used like a variable. inventory[item] on the right of an assignment reads the count, and on the left it stores a new one. The augmented assignment inventory[item] += amount does both: it reads the old count, adds amount, and stores the sum under the same key.
It is shorthand for inventory[item] = inventory[item] + amount, without writing the lookup twice.
The same pattern works with the other augmented operators. After inv["apples"] -= 2 on a dictionary where apples is 5, the count is 3. And inv["apples"] *= 2 doubles it. All of them read the current value, compute, and store the result under the same key.
Don't confuse updating with adding a new entry. Assigning to a key that isn't there, as in inv["pears"] = 4, creates it. But += on a key that isn't there fails, because there is no old value to add to. This lesson stays on the first case: the item is always in stock as a key, even with a count of 0.
Step by step
- Add
amountto the count underitemwith+=. The dictionary is changed in place. - Return
inventory. It already holds the new count, so it is the answer.
The solution in Python
class Solution:
def restock(self, inventory: Dict[str, int], item: str, amount: int) -> Dict[str, int]:
inventory[item] += amount
return inventory
Details worth knowing:
- The caller's dictionary changes too. Dictionaries are mutable, and the function works on the one it was given. After
restock(inv, "bananas", 3), printinginvshows{'apples': 5, 'bananas': 5, 'cherries': 10}, the same as the returned value. To keep the original, copy it first withinventory = dict(inventory). +=needs the key to exist. It reads the old value first, so a missing key raisesKeyError. The lesson guaranteesitemis present. When it might not be,inventory[item] = inventory.get(item, 0) + amountstarts from 0.- Order. The key keeps its place in the dictionary. Updating a value doesn't move the entry.
- A count of 0 is a normal value.
{"milk": 0}with12becomes{'milk': 12}.
Edge cases and common mistakes
- Using
=instead of+=.inventory[item] = amountthrows the old count away. For{"pens": 7, "paper": 3}it would givepensa count of 1 instead of 8. - Quoting the variable.
inventory["item"]is the key spelled i-t-e-m, which doesn't exist. - Returning only the number. The function returns the whole dictionary, not the new count.
Tracing the first example
Before the call, inventory["bananas"] is 2. The statement reads 2, adds amount (3) and stores 5 back under "bananas". The entries for "apples" and "cherries" are never touched, so the function returns {'apples': 5, 'bananas': 5, 'cherries': 10}.
Why return the dictionary at all
Because the dictionary was changed in place, the caller could ignore the return value and still see the update. The lesson asks you to return it anyway, so the function can be used in an expression, and the tests compare the returned dictionary with the expected one. Dictionaries compare by their entries, not by their order, which is why the statement says the order of the entries doesn't matter.
Testing
{"milk": 0},"milk",12gives{'milk': 12}.{"pens": 7, "paper": 3},"pens",1gives{'pens': 8, 'paper': 3}.
