[Tutor] problems with dictionary

Bill Mill bill.mill at gmail.com
Wed Mar 23 21:55:56 CET 2005


On Wed, 23 Mar 2005 20:49:11 -0000, Igor Riabtchuk <igor.r at vodafone.net> wrote:
>  
> Hi, 
> was wondering whether you can help? 
>   
> Say I got a dictionary of keys:values : 
>   
> And what I want to do is depending on what key (a,b,c) the person presses, I
> want to output the value (tom, dic, harry). 
>   
> So I program like this: 
>   
> import Tkinter 
>   
>  
> D={a:"tom", b:"dick", c:"harry"} 
>   
>  
> text.bind('<Key>', self.Conv) 
>   
> def Conv(self,event): 
>     if D.has_key(event.keysym): 
>         str="The name is"+str 
>     self.text.insert(END,str) 
>     return 'break' 
>   

In line 3 of the Conv function, you write "str="The name is" + str .
However, str has yet to be defined, from what I can tell. Thus, Python
should throw a NameError. Unforutnately, you haven't included the
exception that Python gives you with this email, so I can't really
help you much more than that.

To get a value from a dictionary D, simply do:

>>> D = {1:'test', 2:'monkey', 3:'apple'}
>>> D[2]
'monkey'

You should read the Python Tutorial at http://docs.python.org/tut/tut.html .

> (If I had to do each one (i.e. without the dictionary) I would do as
> follows: 
>   
> def Conv(self,event): 
>     if event.keysym==a: 
>     str="tom" 
>     self.text(END, str) 
>     return 'break' 
> ) 
>   
> There is clearly a mistake in the first function, only thing is I cannot
> spot it and thus the thing does not work. 

Send us the exception python gives you and we may be able to help you more.

Peace
Bill Mill
bill.mill at gmail.com


More information about the Tutor mailing list