Get key name from Python KeyError exception

I would like to get the key name from the Python KeyError exception:

For example:

myDict = {'key1':'value1'}
try:
    x1 = myDict['key1']
    x2 = myDict['key2'] 
except KeyError as e:
    # here i want to use the name of the key that was missing which is 'key2' in this example
    print error_msg[missing_key]

i have already tried this

print e
print e.args
print e.message

my code is inside django view !

if i use ipython for example and try e.arg or e.message it works fine. but then i try it while inside a django view i get this results:

"Key 'key2' not found in <QueryDict: {u'key1': [u'value']}>" 
("Key 'key2' not found in <QueryDict: {u'key1': [u'value']}>",) 
Key 'key2' not found in <QueryDict: {u'key1': [u'value']}>

while i just want the 'key2'

Answers


As your dictionary is actually a QueryDict, and therefore returns a different error message, you will need to parse the exception message to return the first word in single quotes:

import re
#...
except KeyError as e:
    m = re.search("'([^']*)'", e.message)
    key = m.group(1)

You can use e.args:

[53]: try:
    x2 = myDict['key2']
except KeyError as e:    
    print e.args[0]
   ....:     
key2

From the docs:

The except clause may specify a variable after the exception name (or tuple). The variable is bound to an exception instance with the arguments stored in instance.args


myDict = {'key1':'value1'}
try:
    x1 = myDict['key1']
    x2 = myDict['key2'] 
except KeyError as e:
    # here i want to use the name of the key that was missing which is 'key2' in this example
    print "missing key in mydict:", e.message

The exception object will be the missing key

a={"a":1}
try:
    print(a["b"])
except KeyError as e:
    print(e)        #prints "b"

For KeyErrors, the 2nd element (index 1) of sys.exc_info() holds the key:

import sys
try:
    x1 = myDict['key1']
    x2 = myDict['key2'] 
except KeyError:
    print 'KeyError, offending key:', sys.exc_info()[1]

Output:

KeyError, offending key: 'key2'


myDict = {'key1':'value1'}
try:
    x1 = myDict['key1']
    x2 = myDict['key2']
except KeyError as e:
    print e.message

in this case will print key2

edited to add...

not familiar with django but if the e.message is consistent (and consistently a string) you could extract the key using normal string methods, something like.

my_non_key = e.message.split(" ")[1]

or a similar regex thing?


Need Your Help

How to access $scope variable in angular from chrome console

angularjs google-chrome-devtools

How to access the scope variable widgets from chrome's console