What is KeyError in Python

In this article, we will see what is a KeyError in Python
The Python compiler throws a KeyError when the key used for a search does not exist in the mapping. A map is a data structure in Python that maps a collection of values onto another collection of values. Dictionary is the most common mapping.
The given below code when executed will throw a KeyError.
#a dictionary to store names and phone numbers sample_dict = {"Alan" : "99898", "Deva" : "32123", "Ann" : "21345"} print(sample_dict["Adil"])
Output:
Traceback (most recent call last): File "C:\Users\user\Desktop\test.py", line 6, in <module> print(sample_dict["Adil"]) KeyError: 'Adil'
The output throws a KeyError because there is no key in the above declared dictionary.
We can use try-except block for handling this exception
#a dictionary to store names and phone numbers sample_dict = {"Alan" : "99898", "Deva" : "32123", "Ann" : "21345"} try: print(sample_dict["Adil"]) except: print("The provided key is not present in the sample_dict")
Subscribe
Login
Please login to comment
0 Discussion