How can I determine the invalid key when handling a KeyError exception?

Question

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
16 Likes

when i tried this syntax i got a type error at “as”, like i couldnt aliasite KeyError as k, why that happens?

1 Like

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 :slight_smile: )

What is “as”? I have never seen this syntax

It is what it sounds like. The value of KeyError is substituted to temporary variable k.

1 Like

why does it have to be converted to a string? what’s the original type and how does this conversion work?

1 Like

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".

I hope I was able to answer your question. Cheers

1 Like

KeyError is a type of error. Also we can all the invalid key from it.
Am I right?

KeyError will tell us that we got an invalid key. If there is more than one KeyError, the console will state all of them. So, you are right

2 Likes

I’m pretty sure what I said is right

Also, is there a way to print “Utah” without quotes?

Hello @xalava!

Can you clarify what you are asking?

When printing strings, the quotation marks required by syntax are usually not printed. Only quotation marks escaped with the \ character will be printed.

Yes, i mean in this situation

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

#Key 'Utah' does not exist

recieve

#Key Utah does not exist

(without quotation marks of Utah)?

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.

2 Likes

Yes it works! Thank you! And it’s still consice)

1 Like