Skip to content Skip to sidebar Skip to footer

Call Function From Within Dictionary

I've been trying to wrap my head around this problem, I've found a few solutions but no joy. Basically I have a dictionary with keys and a corresponding function. The purpose of th

Solution 1:

When you initialise your dictionary like this:

def manual():
    print("Build in progress")

manuals = {'Manual' : manual()}`

the return value of the manual function will be stored in the dict because you call the function during the initialisation (manuals() is a function call). Because the function doesn't return anything, the value stored in the dictionary under the 'Manual' key is NoneType:

>>> type(manuals['Manual'])
<class'NoneType'>

So you have to change the way the dictionary is initialised in order to have a reference to the function stored in the dict. You can do this by not calling the function during the dictionary initialisation (note the missing ()):

>>> manuals = {'Manual' : manual}
>>> type(manuals['Manual'])
<class'function'>

Then all you need is get a reference to the function from the dictionary by using manuals['Manual'], and call that function manuals['Manual']().

>>>manuals['Manual']
<function manual at 0x7fb9f2c25f28>
>>>manuals['Manual']()
Build in progress

Post a Comment for "Call Function From Within Dictionary"