×

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:

  1. Syntax errors
  2. Logical errors
  3. 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

Python Key Error

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

Python Key Error

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

Python Key Error

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

Python Key Error

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

Python Key Error

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

Python Key Error

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

Python Key Error

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

Python Key Error

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:

  1. First, we should check a key before using indexing
  2. For checking a key, we use the keyword called "in".
  3. 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

Python Key Error

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.

Python Key Error

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

Python Key Error

Let us check the name of the student.

Output

Python Key Error

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.


Related Topics

How to Convert String to List In Python?

How to Convert String to List In Python? We all are familiar with what strings and lists are, let us have a quick revision on them- Strings are a sequence of characters...

4 minutes read.

Python Strong Number

Strong Number- Logic Divide each of the number's digits into separate units to determine if it is a strong number or not.The factorial of each digit must then be determined. The...

5 minutes read.

How to plot a Histogram in Python

A Histogram is used to represent a given data provided as a chunk. This histogram is a graphical representation that uses bars to indicate the ranges of the data. In...

4 minutes read.

How to set font for Text in Python

As a tuple with the font family as the first component, a size in point as the second, and possibly a string with one or more of the style modifiers...

5 minutes read.

Python Matrix Multiplication

One of the most fundamental mathematical structures, matrices are used often in many disciplines, including mathematics, physics, engineering, computer science, etc. For example, matrices and associated operations (multiplication and addition) are...

8 minutes read.

Python String endswith() method

Python String endswith() method The string.endswith() method in Python returns a Boolean value True if the string ends with the specified suffix, otherwise it returns False. Syntax endswith(suffix[, start[, end]]) Parameter suffix – This parameter represents a string or tuple...

2 minutes read.

Python Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.

What is Python online compiler?

The compiler is a program that is used to scan an entire high-level program (source code) and it translates the scanned program into machine code. Compilers convert .py source code into...

5 minutes read.

Create First GUI Application using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Executing Shell Commands in Python

This tutorial aims to make us understand what a Shell is, what is the importance of a Shell, what are Shell commands in Python, and how can we execute the...

3 minutes read.

Python bool()

Python bool() class The bool() class in Python returns the boolean value for the specified object. Syntax class bool([x]) Parameter object: This parameter represents the object, like String, List, Number etc. Return It will always return True, except...

1 minute read.

Python Set union() method

Python Set union() method The set.union() method in Python returns a set that contains all items from the original set and all items from the specified sets. Syntax set.union(set1, set2...) Parameter set1- This parameter represents the first set...

2 minutes read.

Python Simple Interest

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 minutes read.

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

6 minutes read.

How to check version of Python

How to check version of python The versions of Python come with different kinds of features and functionalities. It is not a herculean task to keep track of the updates these...

3 minutes read.

Sublime Python

SUBLIME: A compact, cross-platform code editor called Sublime Text 3 (ST3) is well-known for its quickness, usability, and robust community support. Although it's a fantastic editor out of the box, its...

6 minutes read.

Applications of Python

Top 10 Applications of Python in 2020- 2021 Python language is famous for its general-purpose nature, which enables developers to use it in every field of development. Python can be found...

6 minutes read.

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.

AES CTR Python

Python Programming Language  Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.