Differences between revisions 2 and 3
Revision 2 as of 2008-11-15 14:01:01
Size: 759
Editor: localhost
Comment: converted to 1.6 markup
Revision 3 as of 2009-06-09 16:16:17
Size: 759
Editor: 72
Comment: Clarified Wording a bit
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
Python raises a '''KeyError''' whenever a dict() object is requested a value
u
sing format {{{a = adict[key]}}} if key is not in the dictionary.
Python raises a '''KeyError''' whenever a dict() object is requested. Using the format {{{a = adict[key]}}} if the key is not in the dictionary.

Python raises a KeyError whenever a dict() object is requested. Using the format a = adict[key] if the key is not in the dictionary.

If you don't want to have an exception but default value used instead, you can use get() method:

   1 default = 'Scruffy'
   2 a = adict.get('dogname', default)

Even more handy is somewhat controversially-named setdefault(key, val) which sets the value of key only if it is not already in the dict, and returns the value in any case:

   1 default = 'Scruffy'
   2 dog_owned_by = {'Peter': 'Furry', 'Sally': 'Fluffy'}
   3 
   4 dogs = []
   5 for owner in ('Peter', 'Sally', 'Tim'): 
   6     dogs.append(dog_owned_by.setdefault(owner, default))
   7 
   8 # dogs == ['Furry', 'Fluffy', 'Scruffy']

KeyError (last edited 2012-11-20 14:56:07 by yosefcz)

Unable to edit the page? See the FrontPage for instructions.