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 9
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4