Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Emulating Switch/Case – Full Example

Give Feedback

This video concludes the course on Emulating Switch/Case in Python. In this lesson you’ll see a real world example of how you to emulate switch/case using a Python dictionary and lambda functions :

def dispatch_dict(operator, x, y):
    return {
        'add': lambda: x + y,
        'sub': lambda: x - y,
        'mul': lambda: x * y,
        'div': lambda: x / y,
    }.get(operator, lambda: None)()

You’ll also see a potential downside of using this method.

Comments & Discussion

Anonymous on March 28, 2019

How about longer functions that cannot be expressed in single line lambda and the case where each function has different input parameters , such as :

'a': func1(param1, param2),
'b': func2(param1, param2, param3), 
'c': func3(param_1, param_2)

func1(param1, param2): # code to generate hcf of these two params
func2(param1, param2, param3) # code to generate primes of param1, param2, param3
func3(param_1, param_2) # code to genrate LCM of the numbers

I guess code for func1, func2 and func3 cannot be expressed as a lambda funcion.

Even if they can be expressed as a single line lambda func. idea behind this not to know about expressing complex functions into single line lambdas.

All I want is how to have handler functions with long lines of code in them into a dictionary?

Dan Bader RP Team on March 28, 2019

If I understood your example correctly, something like this might work:

def dispatch_dict(op, x, y, z):
    return {
        'a': lambda: func1(x, y),
        'b': lambda: func2(x, y, z),
        'c': lambda: func3(x, y)
    }.get(op, lambda: None)()

Anonymous on April 4, 2019

I tried it and it worked… thanks.. In my code I had to return dict in all cases including the default case, so modified it a bit

def func_default(): return {}

def dispatch_dict(op, x, y, z): return { ‘a’: lambda: func1(x, y), ‘b’: lambda: func2(x, y, z), ‘c’: lambda: func3(x, y) }.get(op, lambda: func_default() )()

Become a Member to join the conversation.