When writing an exception handler for a KeyError, is it possible to know the key that was invalid?
Answer
Yes, the invalid key can be determined from the KeyError exception. The KeyError class has variables which can be examined for the key, but the simplest method is to use the str() function to convert the KeyError into a string which will contain the key. The following example shows an attempt to access a key not in the dictionary resulting in an exception.
population = {"California": {"Los Angeles": 3971883,
"San Diego": 1394928,
"San Jose": 1026908},
"Texas": {"Houston": 2296224,
"San Antonio": 1469845}
}
try:
utah_list = population['Utah']
except KeyError as k:
print("Key " + str(k) + " does not exist")
# Key 'Utah' does not exist
Hei, @poncianodavid! I’m sorry you got that! For me it worked and the code got executed. Maybe you had some white space. I know this doesn’t help much. However, try again! I’m sure you’ll figure it out (of you haven’t already )
You convert the KeyError to a string, so it could print that the key you requested for (in the example above, its “Utah”) doesn’t exist. If you change the value for k variable (for instance, “Moscow”, you will get: Key “Moscow” doesn’t exist".
When printing strings, the quotation marks required by syntax are usually not printed. Only quotation marks escaped with the \ character will be printed.
try:
utah_list = population['Utah']
except KeyError as k:
print("Key " + str(k) + " does not exist")
# Key 'Utah' does not exist
Utah is printed out with quotation marks and str(k) cannot be modified with " \ " escape character to show this marks as in average string. So the marks here are by default unlike as in normal string.
Hense is there a way to exept KeyError and at the same time instead of
The only solution I can think of is to use the .replace() string method on str(k). Then, you would be able to replace all the single quotation marks with an empty string. More information on .replace()here.
Perhaps a more knowledgeable forum member could reply with a better way to accomplish this.