Python dict.setdefault
Keep the first value stored at a given seat key.
A simple example
dict.setdefault
- Start with A = 1
- Do this Insert A = 2 only if absent
- Result A stays 1
Syntax
seats.setdefault(key, first_name)
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyKeep the first reservation for a seat
Two students ask for the same seat at a school play. The desk enters the requests in order and needs the first confirmed student's name to survive the second request.
seats = {}
seats.setdefault("A1", "Mira")
seats.setdefault("A1", "Sam")
print(seats["A1"])
Mira
Both requests use A1 and the first insertion determines the owner.
Reserve the kiln
Two potters ask to use the same afternoon slot. Two people claim the same slot in order. Keep the first recorded name and read it after both requests.
Assign a library carrel
Two students request the only window desk. Two people claim the same slot in order. Keep the first recorded name and read it after both requests.
What to watch for
An existing None counts as a stored value in Python. Java putIfAbsent can replace a null mapping.