Use a dict of functions

suggest change

Another straightforward way to go is to create a dictionary of functions:

switch = {
    1: lambda: 'one',
    2: lambda: 'two',
    42: lambda: 'the answer of life the universe and everything',
}

then you add a default function:

def default_case():
    raise Exception('No case found!')

and you use the dictionary’s get method to get the function given the value to check and run it. If the value does not exist in the dictionary, default_case is run.

>>> switch.get(1, default_case)()
one
>>> switch.get(2, default_case)()
two
>>> switch.get(3, default_case)()
…
Exception: No case found!
>>> switch.get(42, default_case)()
the answer of life the universe and everything

you can also make some syntactic sugar so the switch looks nicer:

def run_switch(value):
    return switch.get(value, default_case)()
>>> run_switch(1)
one

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents