dictionaries

Z

Zach Shutters

ok, i am trying to learn how to use dictionaries and i am having trouble
with this code:

def function1():
print "function1"

def function2():
print "function2"

dict = {"1":function1,"2":function2}
x = input ("1 or 2?")

dict[x]()
 
S

Steven Bethard

Zach Shutters said:
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
 
Z

Zach Shutters

Ok, I get it thanks!

Steven Bethard said:
Zach Shutters said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,008
Latest member
HaroldDark

Latest Threads

Top