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

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

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.

Mahidhar Nyayapati 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)()

Mahidhar Nyayapati 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() )()

carl on Aug. 12, 2020

Nice tutorial!

Near the end of the full example, you discuss pulling the creation of the dict out of the dispatch function, as an optimization. Just wanted to note, that since the lambda’s you define are directly accessing variables from the enclosing scope, you can’t just cut and paste the dict from the dispatch function to (for example) a global assignment.

For those following along who want to try pulling the dispatch table creation out of the function, you’ll need to populate the dict with lambdas that take arguments x and y, like this:

DISPATCH_TABLE = {
    "add": lambda x, y: x + y,
    "sub": lambda x, y: x - y,
    "mul": lambda x, y: x * y,
    "div": lambda x, y: x / y
}

And then you’ll pass the arguments x and y from the dispatch function into the lambda, like so.

def dispatch_op(op, x, y):
    return DISPATCH_TABLE.get(op, lambda x, y: None)(x, y)

John Kinder on Oct. 6, 2020

There are times where you would like certain conditions to run multiple cases. A switch statement can be controlled with break statements, so in C:

    switch(c){
        case 1: puts("One... no break so going to two.");
        case 2: puts("Two... break"); break;
        case 3: puts("Three... break"); break;
        case 4: puts("Four... no break so going to default.");
        default: puts("Default."); break;
    }

If c == 1 I want to execute 1 and 2, thus no break at the end of case 1… same for 4 that cascades to default. I can accomplish the same by updating a received variable, like:

In [1]: def myswitch(c): 
   ...:     if c == 1: 
   ...:         print('One... no break so going to two.') 
   ...:         c = 2 
   ...:     if c == 2: 
   ...:         print('Two... break') 
   ...:         return 
   ...:     if c == 3: 
   ...:         print('Three... break') 
   ...:         return 
   ...:     if c == 4: 
   ...:         print('Four... no break so going to default') 
   ...:     print('Default.') 
   ...:     return 
   ...:                                                                       
In [2]: for i in range(1,6): 
   ...:     print(f'{i}:', end=' ') 
   ...:     myswitch(i) 
   ...:                                                                       
1: One... no break so going to two.
Two... break
2: Two... break
3: Three... break
4: Four... no break so going to default
Default.
5: Default.

Here I just update my variable as needed and use separate if’s and returns where I would be using breaks. Really no big deal and only requires the additional step of updating the variable in order to be caught by subsequent if statements and using returns as breaks. Is there a better way to accomplish this though?

Ghani on Oct. 15, 2020

Great course!

Become a Member to join the conversation.