Adam Rose
Adam Rose

Reputation: 89

Calling a function from within a dictionary

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()
}

Upvotes: 1

Views: 3777

Answers (2)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52143

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

Upvotes: 3

alecxe
alecxe

Reputation: 473863

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:

Upvotes: 10

Related Questions