Replacements for switch statement in Python?


Question

I want to write a function in Python that returns different fixed values based on the value of an input index.

In other languages I would use a switch or case statement, but Python does not appear to have a switch statement. What are the recommended Python solutions in this scenario?

1
1719
9/28/2018 5:16:42 PM

Accepted Answer

You could use a dictionary:

def f(x):
    return {
        'a': 1,
        'b': 2,
    }[x]
1375
9/13/2008 12:38:24 AM

If you'd like defaults you could use the dictionary get(key[, default]) method:

def f(x):
    return {
        'a': 1,
        'b': 2
    }.get(x, 9)    # 9 is default if x not found

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon