Python dict.copy
Take a shallow copy of a price dictionary before editing its entries.
A simple example
dict.copy
- Start with A = 1
- Do this Copy the map, then set original A to 2
- Result Copy still has A = 1
Syntax
printed = prices.copy()
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyKeep the price shown on yesterday's menu
A café changes its soup price after printing yesterday's menu. Accounts needs a snapshot of the earlier price to check old receipts even as the working price list changes.
prices = {"Soup": 4}
printed = prices.copy()
prices["Soup"] = 5
print(printed["Soup"])
4
The integer mapping in the printed copy stays at four.
Save a café price list
A counter freezes the morning menu before an afternoon update. The desk takes a snapshot before changing the working record. What value is visible on the saved copy?
Print a desk assignment
A secretary prints room assignments before moving the club. The desk takes a snapshot before changing the working record. What value is visible on the saved copy?
What to watch for
The copied dictionary remains mutable. A nested mutable price object would still be shared.