KeyError: ‘key_name’
The “KeyError” occurs when you try to access a dictionary key that doesn’t exist in the dictionary. This error typically indicates that you are referencing a key that is not present in the dictionary.
Consider the following code snippet:
student = {‘name’: ‘John’, ‘age’: 20}
print(student[‘grade’])
In this example, the dictionary student
contains the keys 'name'
and 'age'
. However, when you try to access student['grade']
, which is not a valid key in the dictionary, the “KeyError” occurs.