1

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")
1
  • This is one dictionary... Your dict1 should be dict1={"abc":sm.xyz.cdd, ...} (no parenthesis), otherwise you already calling a function. As for the function, what have you tried so far to implement it? Commented Nov 2, 2022 at 10:55

2 Answers 2

2

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)
    

And then you can just call the function with fun("abc","log").

Sign up to request clarification or add additional context in comments.

1 Comment

This is the simple, minimalistic, and "correct" answer
0
dict1={
  "abc":sm.xyz.cdd,
  "def":sm.acf.fdr,
  "ghi":sm.rty.qsd,
}
def fun(key, *args, **vaargs):
    dict1[key](*args, **vaargs)

6 Comments

You forgot the return. And **vaargs are keyword arguments while OP passes arguments as positional arguments (*args). To be more general you should have both - (*args, **kwargs)
I am so sorry, I forgot it, fixed it now, thanks
in this my string that i am passing is args or vaargs?
@priston it is going to be in args list
i didn't understand how to call it how will i call fun("abc","log")
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.