[Tutor] How to control the not existent keys in a dict

Emile van Sebille emile at fenx.com
Mon May 11 01:02:39 CEST 2009


On 5/10/2009 3:48 PM Emilio Casbas said...
> Hello,
> 
> I have some problems testing keys not existent in a dictionary.
> The code works testing existent keys with his corresponding value, but
> If I enter a not existent key, an exception is raised.
> How can I control the not existent key and assign him a default value?
> 
> user at cipher:~/project/programming/python$ python3.0 test.py
> ¿What is your name? KEY-NOT-EXISTENT
> Good Morning KEY-NOT-EXISTENT
> ¿Which is the secret word? any
> Traceback (most recent call last):
>   File "test.py", line 30, in <module>
>     while not correct_password(name,guess,dictionary):
>   File "test.py", line 8, in correct_password
>     if (is_in_dict and password == dict[nombre.capitalize()]):
> KeyError: 'KEY-NOT-EXISTENT'
> 
> -relevant code snippet-
> dictionary = {'Mark': 'python', 'Dave': 'java', 'Ane': 'C++', 'default':'pass'}
> 
> def correct_password(name,password,dict):
>         if (not is_in_dict and password == dict['default']):

Both here...
>                 return 1
>         elif (is_in_dict and password == dict[nombre.capitalize()]):

... and here you're not testing the inputs, you're testing if is_in_dict 
_is_ (which of course it is  as it's defined and ergo is)  -- you need 
to pass it your parameters, ie, 'is_in_dict(nombre,dictionary)'


>                 return 1
>         return 0
> 
> def is_in_dict(nom,dict):

also -- it's not a good ides to shadow built-in names -- better to use a 
different one like n_dict

HTH,

Emile


>         for n in dict:
>                 if nom.lower() == n.lower():
>                         return 1
>         return 0
> -end relevant code snippet-
> 
> Regards
> 
> 
> 
>       
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list