Where You Might See a Python KeyError in the Standard Library
Most of the time, a Python KeyError
is raised because a key is not found in a dictionary or a dictionary subclass, such as os.environ
. There are also some rare cases in which you might see it raised in Python’s standard library, such as the zipfile
module if an item isn’t found in a zip archive.
00:00
The large majority of the time, a Python KeyError
is raised because a key is not found in a dictionary or a dictionary subclass such as os.environ
, for example.
00:10
In rare cases, you may also see it raised in other places in Python’s standard library, such as in the zipfile
module if an item is not found in a ZIP archive.
00:19
However, these places keep the same semantic meaning of the Python KeyError
, which is not finding the key requested. This will make a little more sense when you see an example. First of all, if you import the ZipFile
class from the zipfile
module, then you can try to use the zipfile.ZipFile
class to extract information about the ZIP archive using .getinfo()
. In this case, if you try to extract an item called 'something'
from the ZIP archive, then it will result in a KeyError
.
00:49
This doesn’t really look like a dictionary key lookup. Instead, it’s a call to zipfile.ZipFile.getinfo()
that raises the exception. The traceback also looks a little different, with a little more information given than just the missing key. Here you can see KeyError: "There is no item named 'something' in the archive"
.
01:09
The final thing to note here is that the line that raised the KeyError
isn’t in your code—it’s in the zipfile
code, but the previous lines of the traceback indicate which lines in your code caused the problem.
Become a Member to join the conversation.