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()
}
2
  • 1
    Please try to execute the code and let us know if you have any specific questions. Commented Apr 25, 2016 at 19:10
  • This is already answered here: stackoverflow.com/questions/3061/… Commented Apr 25, 2016 at 19:12

2 Answers 2

10

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:

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

Comments

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

Comments

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.