×

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

Python Dictionary values() method

Python Dictionary values() method The dictionary.values() method in Python returns a view object that displays a list of all the values in the specified dictionary. Syntax dictionary.values() Parameter NA Return This method returns a view object. The...

1 minute read.

Python max() function

Python max() function The max() function in Python returns the largest item in an iterable or the largest of two or more arguments. Syntax max(iterable, *[, key, default])               or max(arg1, arg2, *args[, key])   Parameter arg1, arg2, *args: This...

1 minute read.

STL in Python

Python has many libraries that are very useful and simplify many complex codes. In the same way, STL is also one of the python libraries used for reading and writing...

3 minutes read.

Why learn Python?

All things considered, learning python would be extraordinary, it'll acquaint you with the universe of dynamic programming dialects, if you're somebody who has had a semester of involvement with C. Python...

4 minutes read.

Python String find() method

Python String find() method The string.find() method in Python finds the first occurrence of the specified value and returns the lowest index in the string if the substring sub is found else it...

2 minutes read.

Python pynmea2

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

4 minutes read.

Python Modulo

For basic calculations, Python provides operators. Python supports a broad range of Arithmetic Operators to do arithmetic, as given below: +Addition*Multiplication-Subtraction/Division//Floor division**Exponentiation%Remainder/Modulus As you can see, one of these basic arithmetic operators...

8 minutes read.

Python List pop() method

Python List pop() method The list.pop() method removes the item at the specified position in the list, and return it. If no index is specified, this method removes and returns the last item in the list. Syntax list.pop([i]) Parameter i:...

1 minute read.

Python Skyline

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.

Paramiko Python Example

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python Identifiers

Identifiers in Python User-defined names are identifiers in Python that are used to name variables, functions, classes, modules, and other things. You can create Python identifiers using these rules: As an identifier...

4 minutes read.

How to Take Input in Python

How To Take Input In Python Python has various in-built functions that help in code redundancy. Let's discuss the usage of some functions- ascii() – it returns a readable representation of objects.format()...

4 minutes read.

Find Median of List in Python

The median is an enlightening measurement that is utilized as a proportion of the focal inclination of a circulation. It is equivalent to the centre worth of the conveyance. There...

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

Sklearn linear Model in Python

The most effective and reliable Python machine learning library is Sklearn. Through a Python consistency interface, it offers a variety of effective tools for statistical modeling and machine learning, including...

5 minutes read.

GUI Calendar using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Python Unit Test Cheat String

Python: 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 faster way....

3 minutes read.

StandardScaler in Sklearn

When and How Should You Use StandardScaler? StandardScaler comes into play whenever the properties of the provided dataset change significantly within their ranges or are recorded in different measurement units. Since using...

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

Screen Rotation app Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.