[Solved] "KeyError:0" In Python With A Dictionary

In this article, we will handle Key error, which is an example of a runtime error; the syntax of the code can be working correctly, but during program execution, the program cannot handle it due to a run time error of a key error.

What is a key error?

1. key error it's a type of runtime error that occurs when a key cannot be located in a dictionary
2. Dictionary: The term "dictionary" refers to an unsorted collection of objects that deal with data type keys. They are also known as associative arrays and are Python's version of data structures. They're made up of key-value pairs, with each pair mapping the key to its corresponding value.

Read Also: Different ways to find Square Root in Python

There are five primary methods of dealing with a "KeyError" in Python; let's have a look at them

METHOD 1: GET METHOD


This method is efficient for handling key errors; it works with a dictionary by returning the value of the key. Default is usually returned when the prompted key cannot be located. In the event, a default value is no outputted. The default is none. Hence these conditions ensure that during program execution, the Key error does not occur. Below is how to implement the get method.
 employeeage = {'ken': 40, 'jade': 26, 'mark': 50}
employee = input("Get employee age for: ")
employeeage = employeeage.get(employee)

if employeeage:
    print(f'{employee} is {employeeage} years old.')
else:
    print(f"{employee}'s age is unknown.")

Output:
Get employee age for: john
john's age is unknown.


In this program we can be able to access the ages of employees based on their keys assigned in the dictionary (employeeage). In this case, we don’t have an age for john hence without (get method) we will get a key error but using the get method we prompt the program to fetch the age itself directly rather than the key. Since there is no age assigned to a key for john, it outputs (unknown) rather than a key error.

METHOD 2: TRY-EXCEPT BLOCK METHOD


As executed in the program below, this is a simple and easy method to execute. While using a for loop, iteration usually occurs during program execution. In the event it meets an error, the program stops in the case where you want to check values in a dictionary, and you are not certain of the key values; using the Try-Except method is useful.
This method prevents the program from stopping during execution, and the program skips and tries the next values in the loop.
The code execution is the best example to showcase how it works.

 d = {1: 7, 7: 6}
for i in range(1, 10):
    try:
        print(d[i])
    except KeyError:
        var = 0

Output:
7
6


NB no key error was returned since try-except prevented the program from stopping since the execution outputted only the key values present(7 and 6) and didn’t not prompt to stop execution when other keys such as(4,5,8….) were absent.

METHOD 3: IN OPERATOR METHOD


• When executing a program with dictionaries and keys, understanding the values and their keys is crucial
• hence when checking a specific range of values existing in a dictionary use of IN operator is effective since it will return the values that are only existing without prompting the keyerror
• Let's have a look at the code snippet below
 d = {1: 7, 7: 6}
for i in range(1, 10):
    if i  in d:
        print(d[i])
Output:
7
6

• In this program, we can output keys 7,6 while many other keys are not present in between 1 and 10

METHOD 4: TRY-EXCEPT-ELSE METHOD


• This is another method of dealing with exceptions. The try-except-else pattern includes three blocks: try, except, and else.
• When the try condition does not generate an exception, the else condition in a try-except statement is beneficial. It must, however, adhere to all of the exceptions.

 products = {'Pan': 10, 'cooker': 5, 'aluminium': 25}
item = input('Get product:')
try:
    print(f'The product  {item} is {products[item]}')
except KeyError:
    print(f'The product {item} is not known')
else:
    print(f'There is no error in the statement')

Output:
Get product: fridge
The product fridge is not known
Process finished with exit code.

• In this code snippet, since the fridge has not been assigned any key, it is not part of the dictionary, by using the try-except else method no key error was prompted due to this outcome it rather outputted the variable itself is not known.

METHOD 5: USING EXCEPTION HANDLING METHOD


• The benefit of using this method is that Python has various built-in functions that can be useful when handling errors like key error.
• When using this method, it is efficient since if a key has 0 value in the dictionary, Then after the program executes, the output will not be a 0 key
• Let's have a look at the implementation

 employee_dict = {'Name': 'Morris', 'ID': 1}

try:
    employee_id = employee_dict['ID']
    print(employee_id)

    emp_dep = employee_dict['Department']
    print(emp_dep)
except KeyError as e:
    print('Key Not Found in Employee details:', e)

Output:
1
Key Not Found in Employee details: 'Department'


DISADVANTAGES OF METHODS OF FIXING KEY ERRORS


• Exception handling may fail to detect other errors and only detect runtime errors only for this case.
• Try-except method may cost the computation time of running the program once you use this method.
• In a program with many key errors using these methods multiple times will disorganize and increase code snippets of your program.
• It affects the general performance of the program and bound to specific scenarios.

CONCLUSION


• Python, just like many other programming languages, encounters various programming errors, such as key error, which is a runtime error.
• A key error is caused when a key cannot be located in a dictionary. A dictionary maps keys to values basically.
• Within a range of values, IN operator, is helpful to avoid returning a key error since it outputs only values present.
• Try except and else Methods are used to prevent the program execution from stooping due to a key error.
• These methods may slow down the performance of a program as well as add more code snippets for your program.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry