Library contents

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

  1. Start with A = 3
  2. Do this Subtract 1 for existing A
  3. Result A = 2
The update reads the old value before storing the calculated one.

Syntax

Python 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.py

Reduce 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.

From the programstock = {"Mug": 3}
Result2
lesson.py
stock = {"Mug": 3}
for item in ["Mug", "Bowl"]:
    if item in stock:
        stock[item] -= 1
print(stock["Mug"])
Output
2

The mug entry is updated, while Bowl is never inserted.

Advertisements

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?

Given14 brushes − 3 issued
Worked result11

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?

Given8 cups − 2 issued
Worked result6

What to watch for

The check and assignment are separate operations. Coordinate shared updates when several workers write the same ledger.

Documentation for Dictionary update for existing keys