-1

I am trying to write a switch case using a dictionary, and calling functions from them all. But the {key,value} pairs are all being printed:

def addWord():
    print "Add word"

def searchWord():
    print "Search word"

def displayAll():
   print "display all"


#Executing the choice
def switch_choice(choice):
    switcher = {
            1:addWord(),
            2:searchWord(),
            3:displayAll()
    }.get(choice,"Invalid input")


#MAIN
print "Enter your choice"
print "1.Add new word"
print "2.Search for a word"
print "3.Display all words"

choice=input()

switch_choice(choice)

Output -

Enter your choice
1.Add new word    
2.Search for a word
3.Display all words
1
Add word
Search word
display all

Can anyone please let me know the reason.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
rittik
  • 63
  • 5

1 Answers1

3

You are not storing functions. You are storing the results of the function calls. Do not call the function objects, call the result of the dict.get() call:

switcher = {
    1: addWord,
    2: searchWord,
    3: displayAll,
}.get(choice, lambda: "Invalid input")()

In Python, functions are just objects, and the () part is just a piece of syntax you can apply to any expression; as long at the expression produces something that is callable (like a function object), then Python is fine with that.

Note that I gave the dict.get() method a lambda expression for the default; if the choice value is not a key in the dictionary, you still need to return something that is callable.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343