Library contents

Python Dictionary assignment and lookup

Assign or replace the value under a product key and use the same key to read it.

A simple example

Dictionary assignment and lookup

  1. Start with A = 1
  2. Do this Store 2 at key A
  3. Result A = 2
Looking up the same key now returns the new value.

Syntax

Python syntax
stock[key] = count
Run these examples in Python

Save one example at a time as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Update the count for a shelf label

A shop keeps one inventory entry for each shelf label. After a second delivery arrives, the clerk replaces the old tea count and looks up the current total using the same label.

From the programstock = {"Tea": 3}
Result7
lesson.py
stock = {"Tea": 3}
stock["Tea"] = 7
print(stock["Tea"])
Output
7

The second tea count replaces the first count.

Advertisements

Revise a locker assignment

A rental desk moves the green key from locker 6 to locker 9. The operator assigns the new value to the existing key and reads it back. Which value does the key now hold?

Givengreen → 6, then green → 9
Worked result9

Correct a menu price

A café changes its soup price after reprinting the menu. The operator assigns the new value to the existing key and reads it back. Which value does the key now hold?

Givensoup → 5, then soup → 6
Worked result6

What to watch for

Indexing a missing key raises KeyError. Use get when the application has a meaningful default.

Documentation for Dictionary assignment and lookup