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


When writing an exception handler for a KeyError, is it possible to know the key that was invalid?


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}

    utah_list = population['Utah']

except KeyError as k:
    print("Key " + str(k) + " does not exist")
# Key 'Utah' does not exist

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