1

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()
}
Adam Rose
  • 89
  • 1
  • 7
  • 1
    Please try to execute the code and let us know if you have any specific questions. – thefourtheye Apr 25 '16 at 19:10
  • This is already answered here: http://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a-string-with-the-functions-name-in-python – larslars Apr 25 '16 at 19:12

2 Answers2

9

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:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
3

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
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119