Home > database >  how to pass parameter in a function which is a value of dictionary in python
how to pass parameter in a function which is a value of dictionary in python

Time:11-02

i have two dictionary

dict1 = {
    "abc": sm.xyz.cdd(),
    "def": sm.acf.fdr(),
    "ghi": sm.rty.qsd(),
}

I need to create a function that takes 2 parameters 1st is the key of dict1 and 2nd parameter would be a string and i want the output

fun("abc", "log")

# then this must be my output
sm.xyz.cdd("log")

CodePudding user response:

dict1={
  "abc":sm.xyz.cdd,
  "def":sm.acf.fdr,
  "ghi":sm.rty.qsd,
}
def fun(key, *args, **vaargs):
    dict1[key](*args, **vaargs)

CodePudding user response:

As was mentioned in a comment, you can remove the parentheses when defining the dictionary to store the functions as a value associated with a key. Then you can write a simple function that accesses the function in the dictionary and returns the output with the given input:


def fun(dictKey, funInput):
    
    return dict1[dictKey](funInput)
    
  • Related