Library contents

Python Conditional dictionary assignment

Compare the current room with the change slip before replacing its value.

A simple example

Conditional dictionary assignment

  1. Start with A = 1
  2. Do this Replace 1 with 2 if it still matches
  3. Result A = 2
The comparison and the replacement refer to the same key.

Syntax

Python syntax
if rooms.get(key) == expected
Run these examples in Python

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

python3 lesson.py

Change a room assignment only if it is still current

A receptionist holds a change slip that moves a class from room A2 to B1. Before updating the board, she checks that the displayed entry still matches the room printed on her slip.

From the programrooms = {"Class": "A2"}
ResultB1
lesson.py
rooms = {"Class": "A2"}
if rooms.get("Class") == "A2":
    rooms["Class"] = "B1"
print(rooms["Class"])
Output
B1

The desk applies the slip because the old room matches.

Advertisements

Change a duty room

The old assignment still matches the room printed on the request. The desk replaces the value only when the recorded value matches the expected one. Which value remains?

GivenRecorded West · replace West with East
Worked resultEast

Ignore a stale booking change

A newer room assignment has already been saved. The desk replaces the value only when the recorded value matches the expected one. Which value remains?

GivenRecorded Hall · replace East with Lab
Worked resultHall

What to watch for

Use a sentinel when None is a legitimate expected value and a missing key needs separate treatment.

Documentation for Conditional dictionary assignment