Replacements for switch statement in Python?

Michael Schneider picture Michael Schneider · Sep 13, 2008 · Viewed 1.7M times · Source

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?

Answer

Greg Hewgill picture Greg Hewgill · Sep 13, 2008

You could use a dictionary:

def f(x):
    return {
        'a': 1,
        'b': 2,
    }[x]