Python Key Error
What is an Error?
Errors are nothing but problems in the program which occur in a program code, and this will stop the execution of the program. It is also called an illegal operation that the user performs and will result in the program stopping its execution normally.
When an error occurs, the program will not run or compile until and unless an error is removed. The compiler finds these errors when we write any code mistakes so that we can't even execute them. There are three types of python errors. They are:
- Syntax errors
- Logical errors
- Exceptions
Difference between Error and Exception in Python
Error is the problem in the program when it is written wrong and stops the program's execution. By keeping this aside, exceptions are nothing but internal events that occur inside the program that will cause disturbance to the program execution and stop the execution flow.
Syntax Errors
Every programming language has its syntax. All must follow the syntax to write a program code and execute it accurately. When this syntax is not written or followed correctly, an error indicating syntax error will occur and shows on the screen where and why this error has occurred. These are called compiled time errors because these errors are found at the time of compilation.
Example program to show how the syntax error occurs
for i in range(10)
print(i)
Output

The output shows that we should give the proper syntax for executing the program.
Logical errors
These runtime errors occur when there is no syntax issue but a logic-type problem.
Example Program to show logical errors.
Totalmarks = 100
m = Totalmarks / 0
print(m)
Output

In the above example, an error occurred called ZeroDivisionError because we gave an expression by dividing a number by 0.
There will be an error called Key error in Python, which occurs when the key belonging to the dictionary is not found.
Key Error in Python
When a key is not found in a dictionary, a Key Error exception is raised. That is when we are trying to access an item or a key in a dictionary that is not present in that particular dictionary. So, this raises an exception called key error. Python will not return a value for an item or a key that does not exist in the dictionary.
We know the dictionary means a pair of "key" and "value." An item consists of a "key" associated with a "value".
Here is an example showing the dictionary has keys with values.
Example Program
myDictionary = { 2:4, 3:9, 4:16}
print("My dictionary is:", myDictionary)
print(myDictionary[5])
Output

The output shows a Traceback error because the key "5" does not exist in the dictionary and has no value.
We can avoid these errors in a program code byusing conditional statements, the get() method, Try Exception.
Let us discuss one by one with an example of each method.
Avoid Key Errors using Conditional If else Statements
Using a conditional statement, we can check whether the particular key is present in the pair of key-value pairs. There will be an option to find the key using theindex number of the key.We can check if a particular key is present in the key-value pairs of a dictionary without accessing the value.
This method avoids the Key error exception.
A Sample Program Showing the Use of If else Statements
myDictionary = {2:4, 3:9, 4:16}
print("My dictionary is:", myDictionary)
key = 5
if key in myDictionary.keys():
print(myDictionary[key])
else:
print("{} not in a dictionary".format(key))
Output

The above output shows that the key "5" is not in the given key-value pairs of a dictionary. There is a problem with this method: we have to check whether a given key is present in the given dictionary or not. This method may take much time and can be avoided by using the get() method to access the values from the given dictionary.
Avoid Key Errors Using the get() Method
When we give this get() methodin a program code, it will take the given key and anoptional value as input. If the key we gave in a program is present in the dictionary, it gives the value associated with it as the output.
A Sample Program Showing the Use of the get() method.
myDictionary = {2:4, 3:9, 4:16}
print("My dictionary is:", myDictionary)
key = 3
print("The key is:", key)
print("The associated value is:", myDictionary.get(key))
Output

The above output shows that the get() method is useful for avoiding key errors in Python. We gave the "key" as "3", and it returns the associated value as an output.
Python Key Error
Another Example Using get() Method
myDictionary = {2:4, 3:9, 4:16}
print("Dictionary values are:", myDictionary)
key = 5
print("key value is:", key)
print("Associated value is:", myDictionary.get(key))
Output

The above output shows that the associated value is returned as "None." It is because there is no key associated with "5." So, to return an associated value, we should give the key along with the value shown in the before example. It returns "none" because the key given in our program code is not present in the dictionary; if no optional value is passed, it will return "NONE".
We have another example in the get () method, which is when we pass an optional value to this get () method, and it will return a value even if the given key is not present in that dictionary.
Sample Program
myDictionary = {2:4, 3:9, 4:16}
print("Dictionary values are:", myDictionary)
key = 5
print("key value is:", key)
print("Associated value is:", myDictionary.get(key,25))
Output

As we discussed above, giving an optional value to the get() method will return a key associated with the value even if the key is not present in that dictionary.
We will discuss another method in key error
By Using the Try Except Method
We can use try-except blocks in Python to handle the key error exception.
So, by using this method, we can execute the code to access the value using the given key in the try block and can handle the exception in the except block by the below program.
A Sample Program Using above Method
myDictionary = {2:4, 3:9, 4:16}
print("Dictionary value is:", myDictionary)
key=5
print("key value is:", key)
try:
val=myDictionary[key]
print("The associated value is:", val)
except KeyError:
print("The key is not in the dictionary")
Output

Therefore, the key "5" is not present in the dictionary. So, it has returned "The key is not in the dictionary".
Solutions for Python KeyError
We can handle a dictionary in Python KeyError in many ways:
- First, we should check a key before using indexing
- For checking a key, we use the keyword called "in".
- We can use the try-except block.
Example Program
myDictionary = {"name": "ABC", "class":"C", "rollno":"34"}
get_key = input("The information we retrive is(name,class,rollno)?")
if myDictionary[get_key]:
print("The {} of the student is{}".format(get_key,myDictionary[get_key]))
else:
print("The student is not available")
Output

In the above program, we have used "if" statements to check if the key exists or not.
myDictionary[get_key] will return a value only if the key exists. If our key exists, the "if" block will execute. Otherwise, the "else" statement will execute.
Now, let us try the student's name for the above program code.
Output
The output returned was the student's name, "ABC", and the name was in the program on the list of the dictionary.

This code will not raise a KeyError because we have already checked whether our key exists before using it.
If we use myDictionary[get_key] in the block of the "else" statement, our code will raise a KeyError.
Check the Key before Using "in"
The keyword "in" is one of Python's membership operators, and it will check an item if it is present in a lit of values or not. We can also use this "in" keyword to check if that key is inside the dictionary or not.
We will discuss an example program using the "in" keyword.
Sample Program
myDictionary = {"name": "ABC", "class":"C", "rollno":"34"}
get_key = input("The information we retrive is(name,class,rollno)?")
if get_key in myDictionary:
print("The {} of the student is{}".format(get_key,myDictionary[get_key]))
else:
print("The student is not available")
The above program will check if the key exists before printing the values to the console.
This code will check the value of "get_key" if it is inside the dictionary called "myDictionary." If the given key exists "if" statement will run; otherwise, the "else" statement will run. Let us check the information on the student roll number.
Output

Let us check the name of the student.
Output

Conclusion
The KeyError is raised when you try to access the value from a dictionary that does not exist before we access it. To solve this problem, we can check our key before using it, and we will use it if the key exists.
To handle a KeyError, we can use the try-except block if the problem is not from our code.