[Tutor] Passing perimeters in dictionary values?
Alan Gauld
alan.gauld at btinternet.com
Wed Feb 25 00:50:53 CET 2009
"nathan virgil" <sdragon1984 at gmail.com> wrote in
> selection = raw_input("Choice: ")
> choices = {"0":quit, "1":crit.talk, "2":crit.eat, "3":crit.play}
> choice = choices[selection]
> choice()
>
> so that I can call methods from a dictionary, instead of having an
> excruciatingly long if structure. Unfortunately, the problem I'm
> running
> into with this is that I can't pass any perimeters through the
> dictionary.
Yes you can.
choice(x)
will work
as will
choices[selection](param)
So you can do something like:
selection = raw_input("Choice: ")
param = raw_input('Value: ')
choices = {"0":quit, "1":crit.talk, "2":crit.eat, "3":crit.play}
choice = choices[selection]
choice(param)
Or you can build the param value into the dictionary:
selection = raw_input("Choice: ")
choices = {
"0":(quit, None),
"1":(crit.talk, "Hi there"),
"2":(crit.eat, "Nuts"),
"3": (crit.play, "Soccer")
"4": (crit.play, "Baseball")} # same func different param
choice = choices[selection]
choice[0](choice[1])
There are plenty other ways too.
I
> can't figure out how, for example, I could have an option that calls
> crit.eat(2) and another that calls crit.eat(4).
The question is where are the 2 and 4 coming from?
You could read them from the user or a file in option 1 above
or store them with the function under a different menu in option 2.
Or of course you could just hard code them at call time...
It depends how you want to use it...
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list