CARVIEW |
Select Language
HTTP/2 200
date: Thu, 24 Jul 2025 22:57:25 GMT
server: Apache/2.4.41 (Ubuntu)
vary: Cookie,User-Agent,Accept-Encoding
set-cookie: MOIN_SESSION_443_ROOT_moin=aedb7ebd4a63c6b126c6e3dd43ebc06bf800cb4a; Expires=Thu, 24-Jul-2025 23:57:00 GMT; Max-Age=3600; Secure; Path=/
content-encoding: gzip
content-type: text/html; charset=utf-8
x-clacks-overhead: GNU Terry Pratchett
strict-transport-security: max-age=315360000; includeSubDomains; preload
KeyError - Python Wiki
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:
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.