Start learning free

LESSON 131 OF 673 · DICTIONARIES - CHALLENGES

Restock in Python: Updating a Dictionary Value with +=

Practice Read the full explanation

A shop keeps its stock in inventory, a dict from item names to how many of each item it has. A delivery brings amount more of item. Add amount to the count of item and return the updated dictionary.

Only the count of item changes: every other entry stays as it is. The order of the entries doesn't matter.

 

Example 1:

Input: inventory = {"apples": 5, "bananas": 2, "cherries": 10}, item = "bananas", amount = 3
Output: {"apples": 5, "bananas": 5, "cherries": 10}
Explanation: "bananas" had a count of 2, and 2 + 3 = 5. The apples and the cherries keep their counts.

Example 2:

Input: inventory = {"milk": 0}, item = "milk", amount = 12
Output: {"milk": 12}
Explanation: A count of 0 means the milk was sold out. The delivery brings it to 0 + 12 = 12.

Example 3:

Input: inventory = {"pens": 7, "paper": 3}, item = "pens", amount = 1
Output: {"pens": 8, "paper": 3}
Explanation: One more pen: 7 + 1 = 8.

 

Constraints:

  • item is always a key of inventory.
  • amount is at least 1.
  • Every count is 0 or more.
  • Item names are single lowercase words, and they are all different.
STEP 1 OF 2
    Ctrl + Enter to check

    PYTHON · DICTIONARIES - CHALLENGES

    Restock in Python, explained

    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

    1. Add amount to the count under item with +=. The dictionary is changed in place.
    2. 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), printing inv shows {'apples': 5, 'bananas': 5, 'cherries': 10}, the same as the returned value. To keep the original, copy it first with inventory = dict(inventory).
    • += needs the key to exist. It reads the old value first, so a missing key raises KeyError. The lesson guarantees item is present. When it might not be, inventory[item] = inventory.get(item, 0) + amount starts 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} with 12 becomes {'milk': 12}.

    Edge cases and common mistakes

    • Using = instead of +=. inventory[item] = amount throws the old count away. For {"pens": 7, "paper": 3} it would give pens a 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", 12 gives {'milk': 12}.
    • {"pens": 7, "paper": 3}, "pens", 1 gives {'pens': 8, 'paper': 3}.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free