How to pass arguments to a function inside a dictionary?

As switch case is not available in Python, I made use of dictionary for this to perform arithmetic operation:

a = 10
b = 5

def add(a, b):
    return a + b 

def sub(a, b):
    return a - b

def mul(a, b):
    return a * b

def div(a, b):
    return a / b

def default():
    return "not a valid option"

opt = {
   1: add,
   2: sub,
   3: mul,
   4: div
}

op = 2

def getdetails(op):
    return opt.get(op, default)()

getdetails(op)

How do I pass my a and b value to my function when I enter option which hits the dictionary to call particular function?


Since Python 3.10, there actually is a "switch-case" feature, called pattern matching:

a = 10
b = 5

op = 2

match op:
    case 1:
        print(a + b)
    case 2:
        print(a - b)
    case 3:
        print(a * b)
    case 4:
        print(a / b)
    case _:
        print("not a valid option")

The last case, _, is a wildcard.


For earlier versions you can easily "emulate" something similar to a switch-case:

a = 10
b = 5

op = 2

def case(value):
    return op == value

if case(1):
    print(a + b)
elif case(2):
    print(a - b)
elif case(3):
    print(a * b)
elif case(4):
    print(a / b)
else:
    print("not a valid option")

Or, for keeping with your approach, I would do some small changes to your code:

  • No need to implement all those functions - there is the operator module for that.
  • I wouldn't even bother with a default function - as others mentioned, the different signature will cause you headaches ahead.
  • Instead, I would go for forgiveness instead of permission and assume the op exists, and if there is a KeyError - we know it is the default.
  • Finally, your actual mistake is that you simply didn't pass the arguments - opt.get(op, default)() should simply be opt.get(op, default)(a, b), apart from the problem mentioned above with default.
from operator import add, sub, mul, truediv

a = 10
b = 5

opt = {
   1: add,
   2: sub,
   3: mul,
   4: truediv
}

op = 2

try:
    print(opt[op](a, b))
except KeyError:
    print("not a valid option")