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

Alan Gauld alan.gauld at btinternet.com
Mon May 11 01:59:32 CEST 2009


"Emilio Casbas" <ecasbasj at yahoo.es> wrote

> 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?

One way is to use the get() method of a dictionary:

>>> d = {'Exists': True}

>>> d['Exists']
True
>>> d['Error']
Traceback!!!....
>>> d.get('Error',False)
False

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/





More information about the Tutor mailing list