How to Fix KeyError in Python - How to Fix Dictionary Error in PythonPython is a popular language providing several libraries and functions, making the code more effective and easy. Like any other programming language, Python also has a set of errors and exceptions, including ImportError, CompileError, KeyError, etc. What is KeyError in Python?KeyErrors are the most common errors faced by any Python programmer. A KeyError is an error thrown when a program tries to access a key not in the dictionary specified. The dictionary is a data structure in Python that stores data with labels, or we can say it stores key-value pairs. Each key is unique and has a value associated with it. Let's see a simple example that throws KeyError: Output: --------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[4], line 2 1 keys = {"cat" : 1, "dog" : 2, "monkey" : 3} ----> 2 print(keys["cow"]) KeyError: 'cow' Explanation: We have created a dictionary named keys with different key-value pairs in this. Then, we printed the value associated with the key 'cow'. This key is not present in the dictionary. By default, the compiler will get confused finding the key 'cow' in the dictionary and, thus, throw a KeyError. How to fix this error?The KeyError can be fixed in many ways.
Output: Key not found Explanation: We checked the key "cow" using the 'in' operator with the if statement. It will check if the key is present in the dictionary. If not present, it will print the statement "Key not found".
Output: Key not found Explanation: Using the get( ) function, we checked the key "cow" in the dictionary. It will check whether the key is present or not. If it is not present, it will print the statement "Key not found".
Output: 0 0 0 cat 1 cow 0 dog 2 monkey 3 Explanation: We first imported the defaultdict library from the collection module. Then, we made a dictionary with different key values and added these values to the default dictionary. Then, we tried to access a key "cow", which does not exist in the dictionary using the defaultdict. It will give the value 0 by default. Then, we use a loop statement to access all the key values from the dictionary. It will give the key "cow" with the value 0 and the rest of the key values existing in the dictionary. KeyError in JSON DataPython programs can also encounter the KeyError while working with the JSON data consisting of nested dictionaries. JSON (JavaScript Object Notation) is a data format that stores and modifies structured data. The JSON data is represented as a nested dictionary. Let's see a few examples of key errors in the JSON data. Example: JSON data having information on different employees. Output: --------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[8], line 15 1 emp_data = { 2 "employee": [ 3 { (...) 13 ] 14 } ---> 15 desp = emp_data["employee"][0]["department"] KeyError: 'description' Explanation: We have made JSON data with different details of different employees. Then, we tried to access a key "department," which does not exist in the data. It will throw a key error as we try to access a non-existing key. The KeyError with large and complex JSON data can sometimes be challenging to resolve as it will be hard to find the missing key in huge data. Solving KeyError in JSON dataThe basic and simplest solution for the key error in the JSON data is to check the keys in the nested dictionary before accessing them. This is how we can resolve the key error in the JSON data. Code: Output: No Department found in the Data Explanation: It will check the keys within the nested dictionaries in the data. It will check the non-empty list for all the elements in the data using the if condition. It will check for the key "description" in the emp. It will print the message "No department found in the Data", as no key "department" is present. How to ignore the KeyErrors?The KeyError can be handled using the try and except block. A try-except block is used to handle the faults or exceptions in the programs. Let's understand how to handle the key errors using try and except block with a few examples. Example: Handling the key error in the dictionary Code: Output: No key found Explanation: We tried to access a key, "cow", which does not exist in the dictionary. To handle this error, we used a try-except block. If the key is present, it will print the value. Otherwise, it goes to the except, which prints "No key found". Example: Handling the key error in the JSON data Code: Output: No Department found in the Data Explanation: In this, we made JSON data consisting of employee details. Then, we try to access a non-existing key using the try-except block. If there is any KeyError, it will throw an exception of "No Department found in the data". If there is any index error or type error, it will throw an exception and print "No department found". |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India