Python dictionary key error

In this tutorial, you'll learn how to handle Python KeyError exceptions. They are often caused by a bad key lookup in a dictionary, but there are a few other situations when a KeyError can be raised as well. Knowing how to handle these exceptions is essential to writing good Python code.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python KeyError Exceptions and How to Handle Them

Python’s KeyError exception is a common exception encountered by beginners. Knowing why a KeyError can be raised and some solutions to prevent it from stopping your program are essential steps to improving as a Python programmer.

By the end of this tutorial, you’ll know:

  • What a Python KeyError usually means
  • Where else you might see a KeyError in the standard library
  • How to handle a KeyError when you see it

What a Python KeyError Usually Means

A Python KeyError exception is what is raised when you try to access a key that isn’t in a dictionary (dict).

Python’s official documentation says that the KeyError is raised when a mapping key is accessed and isn’t found in the mapping. A mapping is a data structure that maps one set of values to another. The most common mapping in Python is the dictionary.

The Python KeyError is a type of LookupError exception and denotes that there was an issue retrieving the key you were looking for. When you see a KeyError, the semantic meaning is that the key being looked for could not be found.

In the example below, you can see a dictionary (ages) defined with the ages of three people. When you try to access a key that is not in the dictionary, a KeyError is raised:

>>>

>>> ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33}
>>> ages['Michael']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Michael'

Here, attempting to access the key 'Michael' in the ages dictionary results in a KeyError being raised. At the bottom of the traceback, you get the relevant information:

  • The fact that a KeyError was raised
  • The key that couldn’t be found, which was 'Michael'

The second-to-last line tells you which line raised the exception. This information is more helpful when you execute Python code from a file.

In the program below, you can see the ages dictionary defined again. This time, you will be prompted to provide the name of the person to retrieve the age for:

 1# ages.py
 2
 3ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33}
 4person = input('Get age for: ')
 5print(f'{person} is {ages[person]} years old.')

This code will take the name that you provide at the prompt and attempt to retrieve the age for that person. Whatever you type in at the prompt will be used as the key to the ages dictionary, on line 4.

Repeating the failed example from above, we get another traceback, this time with information about the line in the file that the KeyError is raised from:

$ python ages.py
Get age for: Michael
Traceback (most recent call last):
File "ages.py", line 4, in <module>
  print(f'{person} is {ages[person]} years old.')
KeyError: 'Michael'

The program fails when you give a key that is not in the dictionary. Here, the traceback’s last few lines point to the problem. File "ages.py", line 4, in <module> tells you which line of which file raised the resulting KeyError exception. Then you are shown that line. Finally, the KeyError exception provides the missing key.

So you can see that the KeyError traceback’s final line doesn’t give you enough information on its own, but the lines before it can get you a lot closer to understanding what went wrong.

Where Else You Might See a Python KeyError in the Standard Library

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).

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. However, these places keep the same semantic meaning of the Python KeyError, which is not finding the key requested.

In the following example, you can see using the zipfile.ZipFile class to extract information about a ZIP archive using .getinfo():

>>>

>>> from zipfile import ZipFile
>>> zip_file = ZipFile('the_zip_file.zip')
>>> zip_file.getinfo('something')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/path/to/python/installation/zipfile.py", line 1304, in getinfo
  'There is no item named %r in the archive' % name)
KeyError: "There is no item named 'something' in the archive"

This doesn’t really look like a dictionary key lookup. Instead, it is 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: KeyError: "There is no item named 'something' in the archive".

The final thing to note here is that the line that raised the KeyError isn’t in your code. It is in the zipfile code, but previous lines of the traceback indicate which lines in your code caused the problem.

When You Need to Raise a Python KeyError in Your Own Code

There may be times when it makes sense for you to raise a Python KeyError exception in your own code. This can be done by using the raise keyword and calling the KeyError exception:

Usually, the message would be the missing key. However, as in the case of the zipfile package, you could opt to give a bit more information to help the next developer better understand what went wrong.

If you decide to raise a Python KeyError in your own code, just make sure that your use case matches the semantic meaning behind the exception. It should denote that the key being looked for could not be found.

How to Handle a Python KeyError When You See It

When you encounter a KeyError, there are a few standard ways to handle it. Depending on your use case, some of these solutions might be better than others. The ultimate goal is to stop unexpected KeyError exceptions from being raised.

The Usual Solution: .get()

If the KeyError is raised from a failed dictionary key lookup in your own code, you can use .get() to return either the value found at the specified key or a default value.

Much like the age retrieval example from before, the following example shows a better way to get the age from the dictionary using the key provided at the prompt:

 1# ages.py
 2
 3ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33}
 4person = input('Get age for: ')
 5age = ages.get(person)
 6
 7if age:
 8    print(f'{person} is {age} years old.')
 9else:
10    print(f"{person}'s age is unknown.")

Here, line 5 shows how you can get the age value from ages using .get(). This will result in the age variable having the age value found in the dictionary for the key provided or a default value, None in this case.

This time, you will not get a KeyError exception raised because of the use of the safer .get() method to get the age rather than attempting to access the key directly:

$ python ages.py
Get age for: Michael
Michael's age is unknown.

In the example execution above, the KeyError is no longer raised when a bad key is provided. The key 'Michael' is not found in the dictionary, but by using .get(), we get a None returned rather than a raised KeyError.

The age variable will either have the person’s age found in the dictionary or the default value (None by default). You can also specify a different default value in the .get() call by passing a second argument.

This is line 5 from the example above with a different default age specified using .get():

age = ages.get(person, 0)

Here, instead of 'Michael' returning None, it would return 0 because the key isn’t found, and the default value to return is now 0.

The Rare Solution: Checking for Keys

There are times when you need to determine the existence of a key in a dictionary. In these cases, using .get() might not give you the correct information. Getting a None returned from a call to .get() could mean that the key wasn’t found or that the value found at the key in the dictionary is actually None.

With a dictionary or dictionary-like object, you can use the in operator to determine whether a key is in the mapping. This operator will return a Boolean (True or False) value indicating whether the key is found in the dictionary.

In this example, you are getting a response dictionary from calling an API. This response might have an error key value defined in the response, which would indicate that the response is in an error state:

 1# parse_api_response.py
 2...
 3# Assuming you got a `response` from calling an API that might
 4# have an error key in the `response` if something went wrong
 5
 6if 'error' in response:
 7    ...  # Parse the error state
 8else:
 9    ...  # Parse the success state

Here, there is a difference in checking to see if the error key exists in the response and getting a default value from the key. This is a rare case where what you are actually looking for is if the key is in the dictionary and not what the value at that key is.

The General Solution: try except

As with any exception, you can always use the try except block to isolate the potential exception-raising code and provide a backup solution.

You can use the try except block in a similar example as before, but this time providing a default message to be printed should a KeyError be raised in the normal case:

 1# ages.py
 2
 3ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33}
 4person = input('Get age for: ')
 5
 6try:
 7    print(f'{person} is {ages[person]} years old.')
 8except KeyError:
 9    print(f"{person}'s age is unknown.")

Here, you can see the normal case in the try block of printing the person’s name and age. The backup case is in the except block, where if a KeyError is raised in the normal case, then the backup case is to print a different message.

The try except block solution is also a great solution for other places that might not support .get() or the in operator. It is also the best solution if the KeyError is being raised from another person’s code.

Here is an example using the zipfile package again. This time, the try except block gives us a way to stop the KeyError exception from stopping the program:

>>>

>>> from zipfile import ZipFile
>>> zip = ZipFile('the_zip_file.zip')
>>> try:
...     zip.getinfo('something')
... except KeyError:
...     print('Can not find "something"')
...
Can not find "something"

Since the ZipFile class does not provide .get(), like the dictionary does, you need to use the try except solution. In this example, you don’t have to know ahead of time what values are valid to pass to .getinfo().

Conclusion

You now know some common places where Python’s KeyError exception could be raised and some great solutions you could use to prevent them from stopping your program.

Now, the next time you see a KeyError raised, you will know that it is probably just a bad dictionary key lookup. You will also be able to find all the information you need to determine where the error is coming from by looking at the last few lines of the traceback.

If the problem is a dictionary key lookup in your own code, then you can switch from accessing the key directly on the dictionary to using the safer .get() method with a default return value. If the problem isn’t coming from your own code, then using the try except block is your best bet for controlling your code’s flow.

Exceptions don’t have to be scary. Once you know how to understand the information provided to you in their tracebacks and the root cause of the exception, then you can use these solutions to make your programs flow more predictably.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python KeyError Exceptions and How to Handle Them

In this Python tutorial, we will study How to solve Python dictionary key errors using some examples in python. Moreover, we will also cover these topics.

  • Python dictionary key error handling
  • Python dictionary key error but key exists
  • Python dictionary key error 0
  • Python dictionary key error string
  • Python defaultdict key error
  • Python dict key error none
  • Python dict remove key without error
  • Python dictionary try except key error
  • Python key error nested dictionary
  • In this section, we will discuss what is a key error in the Python dictionary.
  • In Python key error is raised when the key does not exist in the dictionary that is used to look up the value.
  • For example, suppose you have a dictionary that contains key-value pair within the curly brackets and now if you want to get the particular key from the dictionary which does not exist in the given dictionary then it will raise an error.
  • To solve this problem, you can select that item from a dictionary that does exist and you can also handle it by using try-except block.

Example:

my_dict={'U.S.A':15,'France':18,'China':27}

result=my_dict['Japan']
print(result)

In the following given code, we have created a dictionary named ‘my_dict’ that contains elements in the form of key-value pair and then we declared a variable ‘result’ and assign a key element ‘Japan’.

Here is the Screenshot of the following given code.

Python dictionary key error
Python dictionary key error

As you can see in the Screenshot the output displays the keyerror:’japan’ the reason behind this is the key does not exist in the dictionary and it cannot return any value.

Solution

Let’s have a look at the solution to this error by using the get() method

  • In Python, the get() method is used to remove the key error and it will check the condition if the key is found then the value is returned, if not then it will raise an error.
  • This method is used to retrieve a value from the dictionary and it takes two parameters that indicate the key which we want to be searched and the default value is none.

Syntax:

Here is the Syntax of Python get() method

dict.get(key[,value])

Example:

Let’s take an example and check how to solve this key error

Source Code:

my_dict={'U.S.A':15,'France':18,'China':27}

result=my_dict.get('japan',14)
print("Return value:",result)

Here is the execution of the following given code

Solution of Python dictionary key error
Solution of Python dictionary key error

As you can see in the Screenshot the output displays the return value is 14.

Also, check: Python Dictionary duplicate keys

Python dictionary key error handling

  • In this Program, we will discuss how to solve the key-error problem by using exception handling in Python.
  • In Python when your program raises an error or something goes wrong then the try-except method will help the user to catch and handle exceptions.

Example:

Let’s take an example and check how to raise the key error in Python by using handling

my_dictionary = {"George" : 678, "Oliva" : 897, "James" : 156}
  
try:  
  print (my_dictionary["Micheal"])  
except:  
  print ("key error:Key does not contain in dictionary")    

In this example, we have created a dictionary that contains elements in the form of key-value pair and then use the try-except block. This method will check the condition if the key is available in the dictionary then it will display the value of that key and if the key is not available then it will display the message ‘key does not contain in the dictionary’.

Here is the implementation of the following given code.

Python dictionary key error handling
Python dictionary key error handling

Solution:

Let’s have a look at the solution to this error

Source Code:

my_dictionary = {"George" : 678, "Oliva" : 897, "James" : 156}

try:  
  print (my_dictionary["Oliva"])  
except:  
  print ("key error:Key does not contain in dictionary")  

In the above code, we have created a dictionary named ‘my_dictionary’ and then we used the handling concept try-except which means if the ‘oliva’ key is available in a dictionary then it will return the value.

Here is the execution of the following given code

Solution of python key error handling
Solution of python key error handling

As you can see in the Screenshot the output displays the key value that is ‘897‘.

Read: Get First Key in dictionary Python

Python dictionary key error but key exists

  • In this section, we will discuss how to solve the key error but key exists in dictionary Python.
  • To perform this particular task, first, we will create a dictionary by using curly brackets and the elements are separated by commas.
  • To get the key error we are going to use the Python in operator and this operand will check the condition whether a key element is available in the dictionary or not.

Example:

country_name = {'U.S.A':178, 'France':456, 'China':754, 'Australia':345}

 
if 'Germany' in country_name:
    print("Key exist in dictionary")
else:
    print("Key error: Does not contain in dictionary") 

In the above code, we have checked if the ‘Germany’ key exists in a dictionary or not. To do this task first we set the condition if the ‘Germany’ key exists in the dictionary then it will return a value otherwise it will display ‘Key-error’.

Here is the implementation of the following given code.

Python dictionary key error but key exists
Python dictionary key error but key exists

Read: Python dictionary increment value

Python dictionary key error 0

  • In this Program, we will discuss how to solve the key error in the Python dictionary.
  • To do this task, we are going to use the indexing method and it is an easy way to get a dictionary key value.
  • Let’s take an example and we will see how dictionary indexing works and it will also check whether the key is available in a dictionary or not.

Example:

my_dictionary= {16: 'Germany', 19: 'Japan'} 

print(my_dictionary[0]) 

Here is the execution of the following given code

Python dictionary key error 0
Python dictionary key error 0

As you can see in the Screenshot the output displays the key error 0 which means it does not locate the key-value and returns the 0 value.

Let’s have a look at the Solution to this error.

Solution:

my_dictionary= {0: 'Germany', 19: 'Japan'} 

print(my_dictionary[0]) 

In the above code, we have updated the given dictionary ‘my_dictionary’ which means we assigned the key as 0 in the dictionary and set the value ‘Germany’. Once you will execute this code the output displays the ‘Germany’ value.

Here is the Screenshot of the following given code

Solution of Python dictionary key error 0
Solution of Python dictionary key error 0

Read: Python dictionary of lists

Python dictionary key error string

  • In this Program, we will discuss how to solve the key error string in the Python dictionary.
  • In this example, we are going to use the indexing method to get the key error string.
  • To do this task, we will assign the unknown key in the list which is not present in the given dictionary.

Example:

my_dictionary = {'z':178,'y':785,'v':345}

print(my_dictionary['m'])

Here is the Output of the following given code.

Python dictionary key error string
Python dictionary key error string

As you can see in the screenshot, the output displays the key error which means the key string does not exist in the dictionary.

Solution:

Let’s have a look at the solution to this error.

Example:

my_dictionary = {'z':178,'y':785,'v':345}

print(my_dictionary['y'])

In the above code, we have mentioned the key ‘y’ in the list which is available in the given dictionary. Once you will execute this code it will return the value of that specific key.

Here is the implementation of the following given code.

Solution of Python dictionary key error string
Solution of Python dictionary key error string

Read: Python dictionary extend

Python defaultdict key error

In Python defaultdict, it will never generate a key error. Suppose you have a dictionary and now you want to exist a new key by using the default dict method and it takes no arguments, generates a default value for a nonexistent key.

Example:

from collections import defaultdict

my_dict = defaultdict(int)
print(my_dict[4])

Here is the Screenshot of the following given code.

Python defaultdict key error
Python defaultdict key error

Read: Python dictionary multiple keys

Python dict key error none

  • In this section, we will discuss how to get the key error none value in Python dictionary.
  • To perform this particular task we are going to use the dict.get() method. In Python, the get() method is used to remove the key error and it will check the condition if the key is found then the value is returned, if not then it will raise an error.

Syntax:

Here is the Syntax of the dictionary.get() method.

dict.get(key[,value])

Example:

my_dict={'a':12,'b':45}

new_result = my_dict.get('c')
print("Key error:",new_result)

Here is the Screenshot of the following given code.

Python dict key error none
Python dict key error none

As you can see in the screenshot, the output displays the key error None.

Solution:

my_dict={'a':12,'b':45}

new_result = my_dict.get('a')
print(new_result)

In the following given, code we have created a dictionary named ‘my_dict’ that contains elements in the form of key-value pairs. After that, we used the dict.get() method and assign the key element which is available in the dictionary.

Here is the implementation of the following given code.

Solution of Python dict key error none
Solution of Python dict key error none

As you can see in the screenshot, the output displays the return value of a specific key.

Read: How to create an empty Python dictionary

Python dict remove key without error

  • In this Program, we will remove a key from Python dictionary without error.
  • To do this task we are going to use the dict.pop() method and it will remove a specific key from dictionary and retuirn its value.
  • To get the more information regarding dict.pop() method. You can refer our detail article on Python dictionary pop.

Example:

new_dictionary = {'U.S.A':456,'China':123,'Germany':975}

new_result = new_dictionary.pop('China')
print(new_result)
print("After removing the key:",new_dictionary)

You can refer to the below Screenshot.

Python dict remove key without error
Python dict remove the key without error

As you can see in the Screenshot the output displays the ‘China’ key has been removed from the dictionary.

Read: Python Dictionary to CSV

Python dictionary try except key error

  • In this section, we will discuss how to use the try-except block in the Python dictionary and get the key error.
  • In Python, try-except block checks the statement if the code does not execute successfully then the program will end at the line and it generates the error while in case of except code will successfully run.
  • In this example, we will create a dictionary that contains elements in the form of key-value pair and then we will use the try-except block. This method will check the condition if the key is available in the dictionary then it will display the value of that key
  • And if the key is not available then it will display the message ‘key does not contain in the dictionary.

Example:

new_dict = {"U.S.A" : 156, "China" : 2356, "Germany" : 897}
  
try:  
  print (new_dict["Japan"])  
except:  
  print ("key error:Key does not contain in dictionary")  

Here is the Screenshot of the following given code.

Python dictionary try except key error
Python dictionary try-except key error

Solution:

Let’s have a look at the solution to this error.

Source Code:

new_dict = {"U.S.A" : 156, "China" : 2356, "Germany" : 897}
  
try:  
  print (new_dict["Germany"])  
except:  
  print ("key error:Key does not contain in dictionary")  

Here is the implementation of the following given code

Solution of Python dictionary try except key error
Solution of Python dictionary try-except key error

Read: Python dictionary of tuples

Python key error nested dictionary

  • Here we are going to discuss how to solve the key error in Python nested dictionary.
  • To do this task first we will create a nested dictionary and assign multiple dictionaries. Next, we will use the dict.get() method and this method will help the user to remove the key error and it will check the condition if the key is found then the value is returned, if not then it will raise an error.

Example:

my_dict = { 'Country_name': {'Germany': 678},
                'Desgination': {'Developer': 987}}
new_result = my_dict.get('Number')
print("Key error:",new_result)

In the above code, we have used the dict.get() method and within this function, we have assigned the unknown key element. Once you will execute this code the output displays the key error value ‘None’ which means the key we have assigned in an argument is not present in the given dictionary.

Here is the Screenshot of the following given code.

Python key error nested dictionary
Python key error nested dictionary

Solution:

Let’s have a look at the solution to this error.

my_dict = { 'Country_name': {'Germany': 678},
                'Desgination': {'Developer': 987}}
new_result = my_dict.get('Country_name')
print(new_result)

In the above code, we have updated the dict.get() function. In this example, we have assigned the present key which is available in the given dictionary as an argument. Once you will execute this code it will return the value.

Solution of Python key error nested dictionary
Solution of Python key error nested dictionary

You may also like to check the following python tutorials.

  • Python dictionary contains + examples
  • Python dictionary comprehension
  • Python Dictionary Search by value
  • Python dictionary initialize
  • Python dictionary multiple values
  • Python convert dictionary to list

So, in this tutorial, we have learned How to solve Python dictionary key errors using some examples in python. Additionally, we have also covered these topics.

  • Python dictionary key error handling
  • Python dictionary key error but key exists
  • Python dictionary key error 0
  • Python dictionary key error string
  • Python defaultdict key error
  • Python dict key error none
  • Python dict remove key without error
  • Python dictionary try except key error
  • Python key error nested dictionary

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

keyerror in Python – How to Fix Dictionary Error

When working with dictionaries in Python, a KeyError gets raised when you try to access an item that doesn’t exist in a Python dictionary.

Here’s a Python dictionary called student:

student = {
  "name": "John",
  "course": "Python",
}

In the dictionary above, you can access the name «John» by referencing its key – name. Here’s how:

print(student["name"])
# John

But when you try to access a key that doesn’t exist, you get a KeyError raised. That is:

student = {
  "name": "John",
  "course": "Python",
}

print(student["age"])
# ...KeyError: 'age'

This is simple to fix when you’re the one writing/testing the code – you can either check for spelling errors or use a key you know exists in the dictionary.

But in programs where you require user input to retrieve a particular item from a dictionary, the user may not know all the items that exist in the dictionary.

In this article, you’ll see how to fix the KeyError in Python dictionaries.

We’ll talk about methods you can use to check if an item exists in a dictionary before executing a program, and what to do when the item cannot be found.

The two methods we’ll talk about for fixing the KeyError exception in Python are:

  • The in keyword.
  • The try except block.

Let’s get started.

How to Fix the KeyError in Python Using the in Keyword

We can use the in keyword to check if an item exists in a dictionary.

Using an if...else statement, we return the item if it exists or return a message to the user to notify them that the item could not be found.

Here’s an example:

student = {
  "name": "John",
  "course": "Python",
  "age": 20
}

getStudentInfo = input("What info about the student do you want? ")

if getStudentInfo in student:
    print(f"The value for your request is {student[getStudentInfo]}")
else:
	print(f"There is no parameter with the '{getStudentInfo}' key. Try inputing name, course, or age.")

Let’s try to understand the code above by breaking it down.

We first created a dictionary called student which had three items/keys – name, course, and age:

student = {
  "name": "John",
  "course": "Python",
  "age": 20
}

Next, we created an input() function called getStudentInfo: getStudentInfo = input("What info about the student do you want? ").  We’ll use the value from the input() function as a key to get items from the dictionary.

We then created an if...else statement to check if the value from the input() function matches any key in the dictionary:

if getStudentInfo in student:
    print(f"The value for your request is {student[getStudentInfo]}")
else:
	print(f"There is no parameter with the '{getStudentInfo}' key. Try inputing name, course, or age.")

From the if...else statement above, if the value from the input() function exists as an item in the dictionary, print(f"The value for your request is {student[getStudentInfo]}") will run. student[getStudentInfo] denotes the student dictionary with the value gotten from the input() function acting as a key.

If the value from the input() function doesn’t exist, then print(f"There is no parameter with the '{getStudentInfo}' key. Try inputing name, course, or age.") will run telling the user that their input is wrong, with suggestions of the possible keys they can use.

Go on and run the code – input both correct and incorrect keys. This will help validate the explanations above.

How to Fix the KeyError in Python Using a try except Keyword

In a try except block, the try block checks for errors while the except block handles any error found.

Let’s see an example.

student = {
  "name": "John",
  "course": "Python",
  "age": 20
}

getStudentInfo = input("What info about the student do you want? ")

try:
    print(f"The value for your request is {student[getStudentInfo]}")
except KeyError:
    print(f"There is no parameter with the '{getStudentInfo}' key. Try inputing name, course, or age.")

Just like we did in the last section, we created the dictionary and an input() function.

We also created different messages for whatever result we get from the input() function.

If there are no errors, only the code in the try block will be executed – this will return the value of the key from the user’s input.

If an error is found, the program will fall back to the except block which tells the user the key doesn’t exist while suggesting possible keys to use.

Summary

In this article, we talked about the KeyError in Python. This error is raised when we try to access an item that doesn’t exist in a dictionary in Python.

We saw two methods we can use to fix the problem.

We first saw how we can use the in keyword to check if an item exists before executing the code.

Lastly, we used the try except block to create two code blocks – the try block runs successfully if the item exists while the except runs if the item doesn’t exist.

Happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

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.

Related posts:

I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

Before we dive into KeyError in Python, it is important to know how a dictionary in python is set up. The following pointers will be discussed in this article:

  • Dictionary in Python
  • KeyError in Python
  • Handling Mechanism for a KeyError
  • A Generic Solution

Dictionary in Python

The dictionary concept in Python is a random collection of values, which has stored data values like a map. It is unlike other data types that hold only a single value as an element. It holds the key: value pair.

KeyError in Python

The key value makes it more efficient. A colon separates a key and value pair and a ‘comma’ separates each key. This dictionary in python functions similar to a normal dictionary. The respective keys should be unique and of immutable data types such as strings, integers, and tuples, but the key-values can be iterated and is allowed to be of any type. There can be keys, which are strings that refer to numbers and vice versa.

Let us have a look at how a dictionary functions through the below-coded example.

# Creating an empty Dictionary 
Dict = {} 
print("Null dict: ") 
print(Dict) 

# Creating Dictionary with Integer Keys 
Dict = {1: 'Fun', 2: 'And', 3: 'Frolic'} 
print("nDictionary with the use of Integer Keys: ") 
print(Dict) 

# Creating Dictionary with Mixed keys 
Dict = {'Name': 'Arun', 1: [12, 23, 34, 45]} 
print("nDictionary with the use of Mixed Keys: ") 
print(Dict) 

# Creating a Dictionary with dict() method 
Dict = dict({1: 'German', 2: 'language', 3:'is fun'}) 
print("nDictionary with the use of dict(): ") 
print(Dict) 

# A Dictionary having each item as a Pair 
Dict = dict([(1, 'Hello'), (2, 'Bye')]) 
print("nDictionary with each item as a pair: ") 
print(Dict)

KeyError in Python

Since we are clear on what a dictionary in python is and how it works. Now let us see what a key error is. KeyError in Python is raised when you attempt to access a key that is not in a dictionary.

The mapping logic is a data structure that maps one set of data to significant others. Hence, it is an error, which is raised when the mapping is accessed and not found. It is familiar to a lookup error where the semantic bug would be stated as the key you are looking for is not to be found in its memory. This can be better illustrated in the below code.

Here I am trying to access a key called “D” which is not present in the dictionary. Hence, the error is thrown as soon as it finds an exception. However, the remaining keys present in the dictionary, which are printed correctly, have the exact values corresponding to them. 

// 
ages={'A':30,'B':28,'C':33}
print(ages['A'])
print(ages['B'])
print(ages['C'])
print(ages['D'])
//

Handling Mechanism for a KeyError in Python

Anyone who encounters a KeyError can handle it in a responsible way. It is his skill to consider all possible inputs to a certain program and handle any precarious entries successfully.

Depending on your use case, some of these solutions might be better or may also not be the exact solution what you are looking for. Nevertheless, the ultimate goal is to stop unexpected key error exceptions from popping up.

If an error is brought from a dictionary in your own code, you can use .get() to extract either the value at the specified key or a default value. Let us have a look at a sample.

//List of fruits and their prices. 

while(1):
fruits= {'Apple': 300, 'Papaya': 128, 'Kiwi': 233}
fruit= input('Get price for: ')
fruit1 = fruits.get(fruit)
if fruit1:
    print(f'{fruit} is {fruit1} rupees.')
else:
    print(f"{fruit}'s cost is unknown.")

A Generic Solution to KeyError

The usual solution is that you can always use the try-except block to tackle such problems by raising the appropriate code and provide a backup solution. Check out the below code for more clarity.

//
while(1):
 ages = {'Jophi': 12, 'Rao': 20, 'Irvin': 16} 
 person = input('Get age for: ')

 try:
    print(f'{person} is {ages[person]} years old.')
 except KeyError:
    print(f"{person}'s age is unknown.")
//

With this, we come to an end of this KeyError in Python article. I hope this article was informative in throwing light on Python’s KeyError exception and how it could be raised. Also, you may be aware now that in case the problem is a dictionary key lookup in your own code, then you can switch from accessing the key directly on the dictionary to using the .get() method with a default return value.

If the problem is not coming from your own code, then using the try-except block for better controlling your code’s flow.

To get in-depth knowledge of Python along with its various applications, you can enroll now for live Python course training with 24/7 support and lifetime access.

Got a question for us? Mention them in the comments section of “KeyError in Python” and we will get back to you.

Отображение – это структура данных в Python, которая отображает один набор в другом наборе значений. Словарь Python является наиболее широко используемым для отображения. Каждому значению назначается ключ, который можно использовать для просмотра значения. Ошибка ключа возникает, когда ключ не существует в сопоставлении, которое используется для поиска значения.

В этой статье мы собираемся обсудить ошибки keyerror в Python и их обработку с примерами. Но прежде чем обсуждать ошибку ключа Python, мы узнаем о словаре.

Словарь (dict) в Python – это дискретный набор значений, содержащий сохраненные значения данных, эквивалентные карте. Он отличается от других типов данных тем, что имеет только один элемент, который является единственным значением. Он содержит пару ключей и значений. Это более эффективно из-за ключевого значения.

Двоеточие обозначает разделение пары ключа и значения, а запятая обозначает разделение каждого ключа. Этот словарь Python работает так же, как и обычный словарь. Ключи должны быть уникальными и состоять из неизменяемых типов данных, включая строки, целые числа и кортежи.

Давайте рассмотрим пример, чтобы понять, как мы можем использовать словарь (dict) в Python:

 
# A null Dictionary  
Dict = {}  
print("Null dict: ")  
print(Dict)  
  
# A Dictionary using Integers  
Dict = {1: 'Hill', 2: 'And', 3: 'Mountin'}  
print("nDictionary with the use of Integers: ")  
print(Dict)  
  
# A Dictionary using Mixed keys  
Dict = {'Name': 'John', 1: [17, 43, 22, 51]}  
print("nDictionary with the use of Mixed Keys: ")  
print(Dict)  
  
# A Dictionary using the dict() method  
Dict = dict({1: 'London', 2: 'America', 3:'France'})  
print("nDictionary with the use of dict(): ")  
print(Dict)  
  
# A Dictionary having each item as a Pair  
Dict = dict([(1, 'Hello'),(2, 'World')])  
print("nDictionary with each item as a pair: ")  
print(Dict) 

Вывод:

Null dict:  
{} 
nDictionary with the use of Integers:  
{1: 'Hill', 2: 'And', 3: 'Mountin'} 
nDictionary with the use of Mixed Keys:  
{'Name': 'John', 1: [17, 43, 22, 51]} 
nDictionary with the use of dict():  
{1: 'London', 2: 'America', 3: 'France'} 
nDictionary with each item as a pair:  
{1: 'Hello', 2: 'World'} 

Keyerror в Python

Когда мы пытаемся получить доступ к ключу из несуществующего dict, Python вызывает ошибку Keyerror. Это встроенный класс исключений, созданный несколькими модулями, которые взаимодействуют с dicts или объектами, содержащими пары ключ-значение.

Теперь мы знаем, что такое словарь Python и как он работает. Давайте посмотрим, что определяет Keyerror. Python вызывает Keyerror всякий раз, когда мы хотим получить доступ к ключу, которого нет в словаре Python.

Логика сопоставления – это структура данных, которая связывает один фрагмент данных с другими важными данными. В результате, когда к сопоставлению обращаются, но не находят, возникает ошибка. Это похоже на ошибку поиска, где семантическая ошибка заключается в том, что искомого ключа нет в его памяти.

Давайте рассмотрим пример, чтобы понять, как мы можем увидеть Keyerror в Python. Берем ключи A, B, C и D, у которых D нет в словаре Python. Хотя оставшиеся ключи, присутствующие в словаре, показывают вывод правильно, а D показывает ошибку ключа.

 
# Check the Keyerror 
ages={'A':45,'B':51,'C':67} 
print(ages['A']) 
print(ages['B']) 
print(ages['C']) 
print(ages['D']) 

Вывод:

45 
51 
67 
Traceback(most recent call last): 
File "", line 6, in  
KeyError: 'D' 

Механизм обработки ключевой ошибки в Python

Любой, кто сталкивается с ошибкой Keyerror, может с ней справиться. Он может проверять все возможные входные данные для конкретной программы и правильно управлять любыми рискованными входами. Когда мы получаем KeyError, есть несколько обычных методов борьбы с ним. Кроме того, некоторые методы могут использоваться для обработки механизма ошибки ключа.

Обычное решение: метод .get()

Некоторые из этих вариантов могут быть лучше или не могут быть точным решением, которое мы ищем, в зависимости от нашего варианта использования. Однако наша конечная цель – предотвратить возникновение неожиданных исключений из ключевых ошибок.

Например, если мы получаем ошибку из словаря в нашем собственном коде, мы можем использовать метод .get() для получения либо указанного ключа, либо значения по умолчанию.

Давайте рассмотрим пример, чтобы понять, как мы можем обработать механизм ошибки ключа в Python:

 
# List of vehicles and their prices.  
vehicles = {"Car=": 300000, "Byke": 115000, "Bus": 250000} 
vehicle = input("Get price for: ") 
vehicle1 = vehicles.get(vehicle) 
if vehicle1: 
    print("{vehicle} is {vehicle1} rupees.") 
else: 
    print("{vehicle}'s cost is unknown.") 

Вывод:

Get price for: Car 
Car is 300000 rupees. 

Общее решение для keyerror: метод try-except

Общий подход заключается в использовании блока try-except для решения таких проблем путем создания соответствующего кода и предоставления решения для резервного копирования.

Давайте рассмотрим пример, чтобы понять, как мы можем применить общее решение для keyerror:

 
# Creating a dictionary to store items and prices 
items = {"Pen" : "12", "Book" : "45", "Pencil" : "10"} 
try: 
  print(items["Book"]) 
except: 
  print("The items does not contain a record for this key.")   

Вывод:

45 

Здесь мы видим, что мы получаем стоимость книги из предметов. Следовательно, если мы хотим напечатать любую другую пару «ключ-значение», которой нет в элементах, она напечатает этот вывод.

 
# Creating a dictionary to store items and prices 
items = {"Pen" : "12", "Book" : "45", "Pencil" : "10"} 
try: 
  print(items["Notebook"]) 
except: 
  print("The items does not contain a record for this key.")  

Вывод:

The items does not contain a record for this key. 

Заключение

Теперь мы понимаем некоторые распространенные сценарии, в которых может быть выброшено исключение Python Keyerror, а также несколько отличных стратегий для предотвращения их завершения нашей программы.

В следующий раз, когда мы столкнемся с ошибкой Keyerror, мы будем знать, что это, скорее всего, связано с ошибочным поиском ключа словаря. Посмотрев на последние несколько строк трассировки, мы можем получить всю информацию, которая нам понадобится, чтобы выяснить, откуда взялась проблема.

Если проблема заключается в поиске ключа словаря в нашем собственном коде, мы можем использовать более безопасную функцию .get() с возвращаемым значением по умолчанию вместо запроса ключа непосредственно в словаре. Если наш код не вызывает проблемы, блок try-except – лучший вариант для регулирования потока нашего кода.

Исключения не должны пугать. Мы можем использовать эти методы, чтобы наши программы выполнялись более предсказуемо, если мы понимаем информацию, представленную нам в их обратных трассировках, и первопричину ошибки.

Изучаю Python вместе с вами, читаю, собираю и записываю информацию опытных программистов.

Понравилась статья? Поделить с друзьями:
  • Pxe mof exiting pxe rom как исправить
  • Python create error message
  • Pxe m0f ошибка на ноутбуке
  • Python continue on error
  • Python connection error exception