Differences between revisions 6 and 7
Revision 6 as of 2009-10-13 20:52:20
Size: 786
Editor: themisgbo-0
Comment:
Revision 7 as of 2012-11-20 14:56:07
Size: 887
Editor: yosefcz
Comment: wiki restore 2013-01-23
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
Python raises a '''KeyError''' whenever a dict() object is requested (using the format {{{a = adict[key]}}}) and the key is not in the dictionary.
Python raises a '''KeyError''' whenever a dict() object is requested (using the format {{{a = adict[key]}}}) and the key is not in the dictionary.
Line 5: Line 7:
{{{
#!python






{{{#!python
Line 11: Line 18:
Even more handy is somewhat controversially-named `setdefault(key, val)` which sets the value
of the key only if it is not already in the dict, and returns that value in any case:
Line 14: Line 19:
{{{
#!python

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







{{{#!python
Line 20: Line 33:
for owner in ('Peter', 'Sally', 'Tim'):  for owner in ('Peter', 'Sally', 'Tim'):
Line 24: Line 37:
# dog_owned_by == {'Tim': 'Scruffy', 'Peter': 'Furry', 'Sally': 'Fluffy'}

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

If you don't want to have an exception but would rather a default value used instead, you can use the 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 the key only if it is not already in the dict, and returns that 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']
   9 # dog_owned_by == {'Tim': 'Scruffy', 'Peter': 'Furry', 'Sally': 'Fluffy'}

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

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