1

Here I am trying to call a function using dictionary key value.

>>> def hello():
        print('hello')

>>> a = {'+': hello()}

it just prints hello after executing this line.

>>> a['+']

If I call the dictionary using key value, it results nothing. What am I missing here?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
rajini raja
  • 99
  • 3
  • 13

3 Answers3

2

Do not put () while you are using the function name as a value for the dictionary because as soon as python find () it will execute the function. Instead just add the function name a = {'+': hello}

And then use the () while fetching the value from the dictionary

a["+"]()

Ezio
  • 2,837
  • 2
  • 29
  • 45
1

You need a return call.

def hello():
    return 'hello'

Or I think that is what you want

roarkz
  • 811
  • 10
  • 22
1

You should put your callable as the value into the dict and then call it.

>>> def hello():
        print('hello')

>>> a = {'+': hello}

>>> a['+']()
hello
BcK
  • 2,548
  • 1
  • 13
  • 27