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

Emilio Casbas ecasbasj at yahoo.es
Mon May 11 00:48:38 CEST 2009


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']):
                return 1
        elif (is_in_dict and password == dict[nombre.capitalize()]):
                return 1
        return 0

def is_in_dict(nom,dict):
        for n in dict:
                if nom.lower() == n.lower():
                        return 1
        return 0
-end relevant code snippet-

Regards



      


More information about the Tutor mailing list