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.
Congratulations, you made it to the end of the course! What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment in the discussion section and let us know.
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 :
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?