Skip to content

Instantly share code, notes, and snippets.

@anand2312
Created February 5, 2021 14:04
Show Gist options
  • Save anand2312/76e9c27225aaafd6a2df5a89b18591cd to your computer and use it in GitHub Desktop.
Save anand2312/76e9c27225aaafd6a2df5a89b18591cd to your computer and use it in GitHub Desktop.
Understanding KeyErrors

Often while using dictionaries in Python, you may come across an error which looks something like this:

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | KeyError: 3

This error is raised when you try to access a key that isn't present in your dictionary.

How to handle the KeyError.

Option 1: dict.get

The dict.get method will return the value for the key, or None (or a default value that you specify) if the key doesn't exist, and hence will never raise a KeyError.

>>> my_dict = {"foo": 1, "bar": 2}
>>> print(my_dict.get("foo"))
1
>>> print(my_dict.get("foobar"))
None
>>> print(my_dict.get("foobar", 3))    # here 3 is the default value to be returned, in case the key doesn't exist
3
>>> print(my_dict)
{'foo': 1, 'bar': 2}

Option 2: dict.setdefault

The dict.setdefault method is similar to the dict.get, but it will also insert the new key with the default value into the dictionary.

>>> print(my_dict.setdefault("foobar", 3))
None
>>> print(my_dict)
{'foo': 1, 'bar': 2, 'foobar': 3}

The Python defaultdict type behaves almost exactly like a regular Python dictionary, but if you try to access or modify a missing key, then defaultdict will automatically create the key and generate a default value for it. While instantiating a defaultdict, we pass in a function that tells it how to create a default value for missing keys.

>>> from collections import defaultdict
>>> my_dict = defaultdict(int, {"foo": 1, "bar": 2})
>>> print(my_dict)
defaultdict(<class 'int'>, {'foo': 1, 'bar': 2})

In this example, we've used the int function - this means that if we try to access a non-existent key, it provides the default value of 0.

>>> print(my_dict["foobar"])
0
>>> print(my_dict)
defaultdict(<class 'int'>, {'foo': 1, 'bar': 2, 'foobar': 0})

Option 4: Using a try and except block

Of course, you can also just use a simple try and except block to handle this error too!

>>> my_dict = {"foo": 1, "bar": 2}
>>> try:
...   print(my_dict["foobar"])
... except KeyError:
...   # handle it the way you want
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment