2009/5/10 Emilio Casbas <[email protected]>: > > 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? > > u...@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 > > > > > _______________________________________________ > Tutor maillist - [email protected] > http://mail.python.org/mailman/listinfo/tutor >
There's also collections.defaultdict, which you can initialise with a "default value factory" which will generate a value for every attempt to get a non-existent key. It can be a lot of fun with a bit of thought. -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com _______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
