sethserver / Python

Python KeyError: How to Avoid and Handle Dictionary Exceptions

By Seth Black Updated September 27, 2024

One of the more frustrating aspects of idomatic Python is EAFP (easier to ask for permission) over LBYL (look before you leap). Using EAFP on dictionaries leaves us with code that with piles of try/except blocks, or worse, code that crashes when it is given unexpected input. Here is a basic example of some Python code that will crash when executed.

>>> person = {'name': 'seth', 'age': 9999999, 'bald': True} >>> person['name'] 'seth' >>> person['city'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'city'

In order to avoid this issue in a cleaner and more explicit fashion, I recommend generally sticking with dictionary gets. As you can see, instead of raising an error the code returns a pre-determined value and continues executing.

>>> person = {'name': 'seth', 'age': 9999999, 'bald': True} >>> person['name'] 'seth' >>> person.get('city', 'Unknown City') 'Unknown City'

While this breaks the EAFP idiom, it certainly makes your Python code more robust and less likely to crash.

Good luck and happy Pythoning!

-Sethers