Replacements for switch statement in Python?
original source : stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python
————————————————————————————————————–
You could use a dictionary:
def f(x):
return {
'a': 1,
'b': 2,
}[x]
————————————————————————————————————–
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
————————————————————————————————————– I’ve always liked doing it this way
result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}[value](x)
————————————————————————————————————–