keyerror in python how to handle in the dictionary

keyerror in python comes when you access a value in the Dictionary using the Key, but that key is not present in the dictionary. That time compiler raised errorkey in python

What is keyerror in python?

Keyerror in python is a common exception encountered by beginners. sometimes It difficult to find KeyError. The best to debug is to print line by line and analyze.

According to Python’s official documentation, the KeyError is raised when a mapping key is accessed and isn’t found in the mapping. A mapping is a data structure that maps one set of values to another. The most common mapping in Python is the dictionary.

Let’s see Example to know more

dictionary  = { 
    0: "abhi",
    1: "raju",
    2: "gullu"
}

print(dictionary[0]) # abhi
print(dictionary[1]) # raju
print(dictionary[2]) # gullu
print(dictionary[3]) # KeyError: 3

Output:

keyerror in python example output screen

In the Above Example,

  • You can see that the error is in line no. 10 (Key Error ).
  • Here, an error is getting because there is no key (that is 3) in the dictionary variable.

Solution

  • Avoid using keys which is not present in the python Dictionary

Ignoring Error using try-except

dictionary  = { 
    0: "abhi",
    1: "raju",
    2: "gullu"
}

print(dictionary[0]) # abhi
print(dictionary[1]) # raju
print(dictionary[2]) # gullu
try:
    print(dictionary[3]) # KeyError: 3
except:
    print("\nI handled the Ecxception")

Output Screen

keyerror in python example 2  putput screen

What happened in this Example?

  • An error occurred in the try block.
  • try throws the error to except block.
  • Except block ran.

Thank you

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on whatsapp
WhatsApp
Share on reddit
Reddit
Share on telegram
Telegram

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top