I wanna call a function from inside a dictionary. Is it possible? And if so how would i go about doing it?
def function():
pass
my_dic = {
'hello': function()
}
I wanna call a function from inside a dictionary. Is it possible? And if so how would i go about doing it?
def function():
pass
my_dic = {
'hello': function()
}
From what I understand, what you actually mean is how to keep the function reference inside a dictionary to be able to call it later after getting it from the dictionary by key. This is possible since functions are first class objects in Python:
>>> def function():
... print("Hello World")
...
>>> d = {
... 'hello': function # NOTE: we are not calling the function here - just keeping the reference
... }
>>> d['hello']()
Hello World
Relevant thread with some use case samples:
Yes, it is possible. Just like other types, functions can be stored in a dictionary. The problem in your code is, you are storing the return value of the function (which is None
in this case), not the function itself.
Remove the parenthesis ()
and you should be good to go:
>>> my_dic = {
... 'hello': function
... }
>>> my_dic['hello']()
None