Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which key failed in Python KeyError?

If I catch a KeyError, how can I tell what lookup failed?

def poijson2xml(location_node, POI_JSON):   try:     man_json = POI_JSON["FastestMan"]     woman_json = POI_JSON["FastestWoman"]   except KeyError:     # How can I tell what key ("FastestMan" or "FastestWoman") caused the error?     LogErrorMessage ("POIJSON2XML", "Can't find mandatory key in JSON") 
like image 780
QuestionC Avatar asked Apr 17 '14 16:04

QuestionC


People also ask

What's key error in Python?

What is Python KeyError Exception? Python KeyError is raised when we try to access a key from dict, which doesn't exist. It's one of the built-in exception classes and raised by many modules that work with dict or objects having key-value pairs.

How do I check for key errors in Python?

Python: check if dict has key using get() function If given key exists in the dictionary, then it returns the value associated with this key, If given key does not exists in dictionary, then it returns the passed default value argument.

What does KeyError 1 mean in Python?

The Python "KeyError: 1" exception is caused when we try to access a 1 key in a a dictionary that doesn't contain the key. To solve the error, set the key in the dictionary before trying to access it or conditionally set it if it doesn't exist.

How do you handle key errors?

Using try-except The try-except block is one of the best possible ways to handle the KeyError exceptions. It is also useful where the get() and the if and in operators are not supported. Here, in this example, there are two cases— normal case and a backup case.


1 Answers

Take the current exception (I used it as e in this case); then for a KeyError the first argument is the key that raised the exception. Therefore we can do:

except KeyError as e:  # One would do it as 'KeyError, e:' in Python 2.     cause = e.args[0] 

With that, you have the offending key stored in cause.

Expanding your sample code, your log might look like this:

def poijson2xml(location_node, POI_JSON):   try:     man_json = POI_JSON["FastestMan"]     woman_json = POI_JSON["FastestWoman"]   except KeyError as e:     LogErrorMessage ("POIJSON2XML", "Can't find mandatory key '"     e.args[0]     "' in JSON") 

It should be noted that e.message works in Python 2 but not Python 3, so it shouldn't be used.

like image 92
anon582847382 Avatar answered Sep 19 '22 08:09

anon582847382