Start learning free

LESSON 134 OF 673 · DICTIONARIES - CHALLENGES

Sell an Item in Python: Decrement a Count or Delete the Key

Practice Read the full explanation

You get inventory, a dict from item names to how many of each item a shop has. You also get the item a customer just bought.

Sell one item and return the updated dictionary.

The count of item drops by 1. When it reaches 0, remove item from the dictionary. The order of the entries doesn't matter.

 

Example 1:

Input: inventory = {"apples": 5, "pears": 2}, item = "apples"
Output: {"apples": 4, "pears": 2}
Explanation: One apple is sold, so 5 - 1 = 4 apples are left.

Example 2:

Input: inventory = {"cups": 1, "plates": 3}, item = "cups"
Output: {"plates": 3}
Explanation: The last cup is sold. No cups are left, so "cups" is removed.

Example 3:

Input: inventory = {"pen": 1}, item = "pen"
Output: {}
Explanation: The only pen is sold. Nothing is left in the shop.

 

Constraints:

  • item is always a key of inventory.
  • Every count is at least 1.
  • Item names are single lowercase words.
STEP 1 OF 4
    Ctrl + Enter to check

    PYTHON · DICTIONARIES - CHALLENGES

    Sell An Item in Python, explained

    Problem overview

    The method sellItem gets inventory, a dictionary from item names to how many of each item a shop has, and the item a customer just bought. It sells one: the count of item drops by 1, and when it reaches 0, the item is removed from the dictionary. It returns the updated dictionary. The constraints promise that item is always a key and that every count is at least 1, so you never sell something that isn't there.

    Examples:

    • {"apples": 5, "pears": 2} selling "apples" gives {"apples": 4, "pears": 2}.
    • {"cups": 1, "plates": 3} selling "cups" gives {"plates": 3}. The last cup is sold, so the key goes.
    • {"pen": 1} selling "pen" gives {}.

    Approach: work out what is left, then decide

    Two outcomes are possible, depending on how many remain after the sale. If some remain, the item stays with its new count. If none remain, the item must leave the dictionary entirely, because an entry with count 0 would still be a key and the shop would seem to carry it.

    So compute remaining first: the current count minus 1. Reading inventory[item] is safe because the item is always a key. Then branch on remaining: del inventory[item] when it is 0, and store the new count otherwise.

    Step by step

    1. Compute remaining as inventory[item] - 1.
    2. If remaining is 0, delete the key with del inventory[item]: the key and its value go together.
    3. Otherwise, store remaining under item in an else branch. The item stays with its lower count.
    4. Return inventory after the else branch. Only the entry of item changed, or it is gone.

    The solution in Python

    class Solution:
        def sellItem(self, inventory: Dict[str, int], item: str) -> Dict[str, int]:
            remaining = inventory[item] - 1
            if remaining == 0:
                del inventory[item]
            else:
                inventory[item] = remaining
            return inventory
    

    On the three examples it returns:

    {'apples': 4, 'pears': 2}
    {'plates': 3}
    {}
    

    Python uses == to compare and a single = to assign, so remaining == 0 is a question and inventory[item] = remaining is a store. The dictionary passed in is changed in place and returned.

    Edge cases and common mistakes

    • Setting the count to 0 and keeping the key. inventory[item] = remaining alone gives {'cups': 0, 'plates': 3} for the second example. The tests expect the key to be gone.
    • Deleting and then storing. If the store runs after the del, the key comes back with count 0. That is why the store is in an else branch.
    • Reading after the delete. After del inventory[item], inventory[item] raises a KeyError. Compute remaining before deleting.
    • Selling other items. Only item changes. Every other entry, like pears and plates above, stays as it was.

    Testing

    Try a count of exactly 2. With {"cups": 2, "plates": 3}, the first sale of "cups" gives {'cups': 1, 'plates': 3}, and the key stays because only 0 deletes it. Selling "cups" again from that result gives {'plates': 3}. Counts of 1 are the edge that separates the two branches, so test one on its own as well.

    It also helps to compare what the shop would say. After the first sale "cups" in inventory is still True, because some cups remain, and after the second it is False. That check is the real meaning of the rule: a key means the shop carries the item.

    Keep going with Python500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free