python key error

Python Key Error: How Can You Fix it Fast?

The Key Error exception in Python is an exception that most programmers encounter especially when they are getting started with Python dictionaries.

In this article you will learn:

  • What does key error mean in Python
  • How to fix key errors in Python
  • How to handle key errors

What does key error mean?

A Key Error is a way for Python to tell you that you are trying to access a key that doesn’t exist in a dictionary.

Here’s an example, I create a file called keyerror.py…

I define a dictionary that contains countries and their capitals.

First I print the capital of Italy….

…then I print the capital of France.

countries = {'Italy': 'Rome', 'Poland': 'Warsaw', 'UK': 'London'}

print(countries['Italy'])
print(countries['France'])

And here’s what I get when I run it:

Rome
Traceback (most recent call last):
  File "keyerror.py", line 3, in <module>
    print(countries['France'])
KeyError: 'France'

As you can see the value related to the first key of the dictionary (Italy) is printed as we want.

But something happens with the second print statement.

A KeyError appears in the output, and that’s because…

Python raises a KeyError when you attempt to access a key that doesn’t exist in a dictionary.

In this case the key ‘France’ doesn’t exist in the countries dictionary.

Notice also how Python can tell at which line of the code the exception has occurred. This is very useful to find the cause of the error quickly when you have hundreds or thousands of lines of code.

Core skill: When Python raises an exception a traceback is included. A traceback is used to give you all the details you need to understand the type of exception and to find what has caused it in your code. 

Makes sense?

How do I fix key errors in Python?

There are two very basic fixes for the key error if your program is simple:

  1. Avoid referencing the key that doesn’t exist in the dictionary: this can make sense if, for example, the value of the key has been misspelled. It doesn’t apply to this specific case.
  2. Add the missing key to the dictionary: in this case we would add ‘France’ as a key to the dictionary as part of its initial definition.

But those are not robust approaches and don’t prevent a similar error from occurring again in the future.

Let’s look instead at other two options…

First option

Tell Python not to return a KeyError if we try to access a key that doesn’t exist in the dictionary, but to return a default value instead.

Let’s say we want to return the default value ‘Unknown’ for any keys not present in the dictionary…

Here is how we can do it using the dictionary get() method:

countries = {'Italy': 'Rome', 'Poland': 'Warsaw', 'UK': 'London'}
default = 'Unknown'

print(countries.get('Italy', default))
print(countries.get('France', default))

And the output becomes:

Rome
Unknown

So, at least in this way we have more control over the way our program runs.

Second option

Verify if a key exists in a dictionary using the in operator that returns a boolean (True or False) based on the existence of that key in the dictionary.

In the example below I use the in operator together with an if else Python statement to verify if a key exists before accessing its value:

countries = {'Italy': 'Rome', 'Poland': 'Warsaw', 'UK': 'London'}

if 'France' in countries:
    print("The capital of France is %" % countries['France'])
else:
    print("The capital of France is unknown")

When I run it I see…

The capital of France is unknown

This is also a good option!

How do you handle key errors?

In the previous section I have introduced the dictionary get() method as a way to return a default value if a key doesn’t exist in our dictionary.

But, what happens if we don’t pass the default value as second argument to the get() method?

Let’s give it a try, being familiar with built-in methods makes a big difference when you write your code:

countries = {'Italy': 'Rome', 'Poland': 'Warsaw', 'UK': 'London'}

print(countries.get('Italy'))
print(countries.get('France'))

Do you know what the output is?

Rome
None

Interestingly this time Python doesn’t raise a KeyError exception…

…the get() method simply returns None if the key doesn’t exist in the dictionary.

This means that we can implement conditional logic in our code based on the value returned by the get() method. Here’s an example:

countries = {'Italy': 'Rome', 'Poland': 'Warsaw', 'UK': 'London'}
  
capital = countries.get('France')

if capital:
    print("The capital is %s" % capital)
else:
    print("The capital is unknown")

The output is:

The capital is unknown

A nice way to avoid that ugly exception 🙂

Avoiding the KeyError with a For Loop

Often a way to handle errors is by using programming constructs that prevent those errors from occurring.

I have mentioned before that a KeyError occurs when you try to access a key that doesn’t exist in a dictionary.

So, one way to prevent a KeyError is by making sure you only access keys that exist in the dictionary.

Ok, but how?

You could use a for loop that goes through all the keys of the dictionary…

This would ensure that only keys that are present in the dictionary are used in our code.

Let’s have a look at one example:

countries = {'Italy': 'Rome', 'Poland': 'Warsaw', 'UK': 'London'}

for key in countries:
    print("The capital of %s is %s" % (key, countries[key]))

And the output is…

The capital of Italy is Rome
The capital of Poland is Warsaw
The capital of UK is London

A for loop can be used to go through all the keys in a dictionary and to make sure you don’t access keys that are not part of the dictionary. This prevents the Python KeyError exception from occurring.

The Generic Approach For Exceptions

Finally, a generic approach you can use with any exceptions is the try except block.

This would prevent Python for raising the KeyError exception and it would allow you to handle the exception in the except block.

This is how you can do it in our example:

countries = {'Italy': 'Rome', 'Poland': 'Warsaw', 'UK': 'London'}
  
try:
    print('The capital of France is %s' % countries['France'])
except KeyError:
    print('The capital of France is unknown')

As you can see, in this case, the except block is written specifically to handle the KeyError exception.

In this case we could have also used a generic exception (removing KeyError)…

try:
    print('The capital of France is %s' % countries['France'])
except:
    print('The capital of France is unknown')

So, do we really need to specify the exception type?

It can be very handy if the try code block could raise multiple types of exceptions and we want to handle each type differently.

Conclusion

Now you have a pretty good idea on how to handle the KeyError exception in Python.

Few options are available to you, choose the one you prefer…

Are you gonna use the get() method or the in operator?

Do you prefer the try except approach?

Let me know in the comments below 🙂

The Python Starter Checklist

Are you getting started with Python?

I have created a checklist for you to quickly learn the basics of Python. You can download it here for free.

Share knowledge with your friends!

Leave a Reply

Your email address will not be published. Required fields are marked *