Replacements for switch statement in Python?

Better Stack Team
Updated on February 3, 2023

In Python, the if-elif-else statement can be used as a replacement for a switch statement. Additionally, the dict.get() method or a dictionary of functions can also be used to achieve a similar effect.

Here are a few examples of using the if-elif-else statement as a replacement for a switch statement in Python:

 
def switch_example(case):
    if case == 'a':
        return 'Case A'
    elif case == 'b':
        return 'Case B'
    elif case == 'c':
        return 'Case C'
    else:
        return 'Other Case'

print(switch_example('a')) # 'Case A'
print(switch_example('b')) # 'Case B'
print(switch_example('c')) # 'Case C'
print(switch_example('d')) # 'Other Case'

Here is an example of using the dict.get() method as a replacement for a switch statement in Python:

 
def switch_example(case):
    options = {
        'a': 'Case A',
        'b': 'Case B',
        'c': 'Case C',
    }
    return options.get(case, 'Other Case')

print(switch_example('a')) # 'Case A'
print(switch_example('b')) # 'Case B'
print(switch_example('c')) # 'Case C'
print(switch_example('d')) # 'Other Case'

And here is an example of using a dictionary of functions as a replacement for a switch statement in Python:

 
def case_a():
    return 'Case A'

def case_b():
    return 'Case B'

def case_c():
    return 'Case C'

def other_case():
    return 'Other Case'

def switch_example(case):
    options = {
        'a': case_a,
        'b': case_b,
        'c': case_c,
    }
    return options.get(case, other_case)()

print(switch_example('a')) # 'Case A'
print(switch_example('b')) # 'Case B'
print(switch_example('c')) # 'Case C'
print(switch_example('d')) # 'Other Case'

All of the above examples show different ways of achieving similar functionality as switch statements in python.