python switch case statement

Python doesn't have switch case statements.

But I found code that will simulate a switch case statement

result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}[value](x)

to catch an error if no key found

try:
{'option1': function1,
'option2': function2,
'option3': function3,
'option4': function4}[value]()
except KeyError:
# default action

I would probably use

switch = {'option1': function1,
'option2': function2,
'option3': function3,
'option4': function4}
if value in switch:
switch[value]()
else:
pass
#default

Comments

V'Raj Kanwade said…
How about this for a default switch case?

http://www.wellho.net/resources/ex.php4?item=y103/python_switch_case
Tom Leo said…
Wow I was kind of disappointed that that python didn't have a case switch feature, but I think this is way cooler!

Popular posts from this blog

Vim vi how to reload a file your editing