Venomed
Venomed

Reputation: 135

Dictionary integer as key and function as value?

This is my code:

def test1():
  print("nr1")

def test2():
  print("nr2")

def test3():
  print("nr3")

def main():
  dictionary = { 1: test1(), 2: test2(), 3: test3() }
  dictionary[2]

if __name__ == "__main__":
  main()

This code returns:

nr1
nr2
nr3

What do I need to change in the code to get this:

nr2

I'm using Python 2.7.13.

Upvotes: 5

Views: 9133

Answers (3)

Mark Tolonen
Mark Tolonen

Reputation: 178001

The line below actually calls each function and stores the result in the dictionary:

dictionary = { 1: test1(), 2: test2(), 3: test3() }

This is why you see the three lines of output. Each function is being called. Since the functions have no return value, the value None is stored in the dictionary. Print it (print(dictionary):

{1: None, 2: None, 3: None}

Instead, store the function itself in the dictionary:

dictionary = { 1: test1, 2: test2, 3: test3 }

Result of print(dictionary):

{1: <function test1 at 0x000000000634D488>, 2: <function test2 at 0x000000000634D510>, 3: <function test3 at 0x000000000634D598>}

Then use a dictionary lookup to get the function, and then call it:

dictionary[2]()

Upvotes: 3

MSeifert
MSeifert

Reputation: 152765

Omit the function calls when creating the dictionary and just call what dictionary[2] returns:

def main():
  dictionary = { 1: test1, 2: test2, 3: test3 }
  dictionary[2]()

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599876

Don't call the functions inside the dict; call the result of the dict lookup.

dictionary = { 1: test1, 2: test2, 3: test3 }
dictionary[2]()

Upvotes: 8

Related Questions