PCEP Certified Entry-Level Python Programmer (PCEP-30-0X) Practice Exam

Session length

1 / 20

When indexing a dictionary with a non-existent key, what exception is raised?

ValueError

TypeError

KeyError

When indexing a dictionary using a key that does not exist, a KeyError is raised. This exception specifically indicates that the requested key cannot be found in the dictionary.

Dictionaries in Python are designed to hold key-value pairs, and each key must be unique within its own scope. When you attempt to access a key that is not present, Python does not find a corresponding value to return, which leads to the exception being raised.

For instance, if you have a dictionary defined as `my_dict = {'a': 1, 'b': 2}`, and you try to access `my_dict['c']`, since 'c' is not defined in the dictionary, Python raises a KeyError. This behavior is crucial for debugging, as it alerts the programmer that there has been an attempt to access an invalid key in the data structure.

IndexError

Next Question
Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy