Python Switch Case trick


Simulate Switch Case in python ...

As we know python won’t provide switch case statement we obviously end with writing if else statements.
Since everything in python is object, we can simulate Switch case statements using dictionary and keys.. J

Here is the code which shows switch case with default stamen executed

While accessing values from dictionary use “dictionary.get( key )” instead dictionary[“key”]

def home_fun():
    print "this is home"
 
def office_fun():
    print "this is office"
 
def school_fun():
    print "this is school"
 
def default():
    print "this is Default"
 
def case_stmt(arg):
    case = {"home":home_fun, "office":office_fun, "school":school_fun}
    if case.get(arg):case.get(arg)()
    default()

if __name__ == "__main__" 
    case_stmt("home")

output
---------
this is home

this is Default


Replace default() with else default() to execute if no matches are found..
when case_stmt("home") is called "home" is mapped to home_fun function.