dictionaries

Steven Bethard steven.bethard at gmail.com
Fri Sep 10 17:04:31 EDT 2004


Zach Shutters <zshutters <at> comcast.net> writes:
> 
> def function1():
>     print "function1"
> 
> def function2():
>     print "function2"
> 
> dict = {"1":function1,"2":function2}
> x = input ("1 or 2?")
> 
> dict[x]()

Right idea, wrong type.  From the docs at:

http://docs.python.org/lib/built-in-funcs.html

] input( [prompt]) 
] 
]      Equivalent to eval(raw_input(prompt)). 

This means that when you use input, it will convert the "1" typed at the 
prompt to the integer 1.  So your code should either be:

>>> d = {1:function1, 2:function2}
>>> x = input("1 or 2? ")
1 or 2? 1
>>> d[x]()
function1
>>>

or

>>> d = {"1":function1, "2":function2}
>>> x = raw_input("1 or 2? ")
1 or 2? 1
>>> d[x]()
function1

You also probably shouldn't name your dictionary 'dict' because then you 
rebind the name 'dict', which is already the builtin 'dict' function.

Steve




More information about the Python-list mailing list