Key error handling python

Python KeyError Exceptions and How to Handle Them

Table of Contents

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

Free Bonus: Click here to get our free Python Cheat Sheet that shows you the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

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:

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.

Note: When an exception is raised in Python, it is done with a traceback. The traceback gives you all the relevant information to be able to determine why the exception was raised and what caused it.

Learning how to read a Python traceback and understanding what it is telling you is crucial to improving as a Python programmer. To learn more on Python tracebacks, check out Understanding the Python Traceback

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:

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:

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

Note: Like the example above, most of the other examples in this tutorial make use of f-strings, which were introduced in Python 3.6.

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() :

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.

Читайте также:  Php include gives error

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:

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:

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() :

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:

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:

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:

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

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

About Chad Hansen

Chad is an avid Pythonista and does web development with Django fulltime. Chad lives in Utah with his wife and six kids.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Master Real-World Python Skills With Unlimited Access to Real Python

Читайте также:  Lenovo s10 3 прошивка биоса

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Master Real-World Python Skills
With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Related Tutorial Categories: basics python

Источник

Python dictionary key error

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

Table of Contents

Python dictionary key error

  • 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:

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.

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.

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

Example:

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

Source Code:

Here is the execution of the following given code

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

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

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.

Solution:

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

Source Code:

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

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

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:

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 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:

Here is the execution of the following given code

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

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

Solution:

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

Читайте также:  Unknown api error перевод

Here is the Screenshot of the following given code

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:

Here is the Output of the following given code.

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:

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.

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:

Here is the Screenshot of the following given code.

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.

Example:

Here is the Screenshot of the following given code.

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

Solution:

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.

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

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:

You can refer to the below Screenshot.

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

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:

Here is the Screenshot of the following given code.

Solution:

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

Source Code:

Here is the implementation of the following given code

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:

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.

Solution:

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

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.

You may also like to check the following python tutorials.

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

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.

Источник

Smartadm.ru
Adblock
detector