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:


Dictionary:
* Avoiding KeyError Exceptions

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
26 Dictionary
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve