Avoiding KeyError Exceptions

suggest change

One common pitfall when using dictionaries is to access a non-existent key. This typically results in a KeyError exception

mydict = {}
mydict['not there']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'not there'

One way to avoid key errors is to use the dict.get method, which allows you to specify a default value to return in the case of an absent key.

value = mydict.get(key, default_value)

Which returns mydict[key] if it exists, but otherwise returns default_value. Note that this doesn’t add key to mydict. So if you want to retain that key value pair, you should use mydict.setdefault(key, default_value), which does store the key value pair.

mydict = {}
print(mydict)
# {}
print(mydict.get("foo", "bar"))
# bar
print(mydict)
# {}
print(mydict.setdefault("foo", "bar"))
# bar
print(mydict)
# {'foo': 'bar'}

An alternative way to deal with the problem is catching the exception

try:
    value = mydict[key]
except KeyError:
    value = default_value

You could also check if the key is in the dictionary.

if key in mydict:
    value = mydict[key]
else:
    value = default_value

Do note, however, that in multi-threaded environments it is possible for the key to be removed from the dictionary after you check, creating a race condition where the exception can still be thrown.

Another option is to use a subclass of dict, collections.defaultdict, that has a default_factory to create new entries in the dict when given a new_key.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents