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.
Don't call the functions inside the dict; call the result of the dict lookup.
dictionary = { 1: test1, 2: test2, 3: test3 }
dictionary[2]()
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]()
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]()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With