Library contents

Python dict.setdefault

Keep the first value stored at a given seat key.

A simple example

dict.setdefault

  1. Start with A = 1
  2. Do this Insert A = 2 only if absent
  3. Result A stays 1
The key already exists, so the original value is kept.

Syntax

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

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

From the programseats = {}
ResultMira
lesson.py
seats = {}
seats.setdefault("A1", "Mira")
seats.setdefault("A1", "Sam")
print(seats["A1"])
Output
Mira

Both requests use A1 and the first insertion determines the owner.

Advertisements

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.

GivenFirst Lin · next Bo
Worked resultLin

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.

GivenFirst Dev · next Uma
Worked resultDev

What to watch for

An existing None counts as a stored value in Python. Java putIfAbsent can replace a null mapping.

Documentation for dict.setdefault