Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 951
Venomed Avatar asked Aug 01 '17 16:08

Venomed


Video Answer


3 Answers

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

dictionary = { 1: test1, 2: test2, 3: test3 }
dictionary[2]()
like image 71
Daniel Roseman Avatar answered Sep 16 '22 14:09

Daniel Roseman


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]()
like image 22
MSeifert Avatar answered Sep 17 '22 14:09

MSeifert


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]()
like image 38
Mark Tolonen Avatar answered Sep 16 '22 14:09

Mark Tolonen