Python Dictionary update for existing keys
Recalculate the quantity only when an item already has a stock entry.
A simple example
Dictionary update for existing keys
- Start with A = 3
- Do this Subtract 1 for existing A
- Result A = 2
Syntax
if item in stock
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyReduce only the stock that is on the ledger
A storeroom issues one mug and receives a request for an unlisted bowl. The clerk should reduce the mug balance but leave the unlisted product out of the ledger.
stock = {"Mug": 3}
for item in ["Mug", "Bowl"]:
if item in stock:
stock[item] -= 1
print(stock["Mug"])
2
The mug entry is updated, while Bowl is never inserted.
Issue paintbrushes
A class has fourteen brushes under its art-room key. An existing stock record is reduced by the number handed out. What value is written back under the same key?
Update a mug count
The café has eight cups on its stock card. An existing stock record is reduced by the number handed out. What value is written back under the same key?
What to watch for
The check and assignment are separate operations. Coordinate shared updates when several workers write the same ledger.