What's wrong with python switch writing like that?

when writing switch-like logic, python

switch = {
    "a":print(1),
    "b":print(2),
    "c":print(3)
}
try:
    switch["c"]
except KeyError as e:
    pass
The output of

this is 1 2 3 instead of the expected 3. Ask what is the reason for this

Mar.20,2022

do not use print in dict.

The

print function executes before it is assigned to switch, so 1 / 2 / 3 is printed, when in fact, switch is {"a": None, "b": None, "c": None} , because the return value of print is None.

you can write:

switch = {"a": 1, "b": 2, "c": 3}
try:
    print(switch["c"])
except KeyError as e:
    pass
Menu