Reputation: 41
def doblue (): print "The sea is blue"
def dogreen (): print "Grass is green"
def doyellow (): print "Sand is yellow"
def redflag ():
print "Red is the colour of fire"
print "do NOT play with fire"
def errhandler ():
print "Your input has not been recognised"
takeaction = {
"blue": doblue,
"green": dogreen,
"yellow": doyellow,
"red": redflag}
colour = raw_input("Please enter red blue green or yellow ")
takeaction.get(colour,errhandler)()
what if I have to pass some parameters to the doblue() or any function of that kind??
Upvotes: 2
Views: 3266
Reputation: 72745
You need to rewrite the doblue
and other functions to receive arguments (optional or otherwise) like so
def doblue (item): print "The {} is blue".format(item)
Then you have the change your dispatch code to look like this
takeaction[colour](item).
This will pass item
to your function.
On a more general point, your understanding of how dictionary dispatching works seems to be incomplete based your assumptions in this question. You need to revisit how it works before trying out stuff like this.
Upvotes: 3