Get key name from Python KeyError exception

Question:

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’

Asked By: yossi

||

Answers:

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
Answered By: Holger

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

Answered By: Ashwini Chaudhary

The exception contains information about the missing key, for example you can print it:

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

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’

Answered By: GreenMatt

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)
Answered By: Jon Cairns

Simply, the response of the KeyError is the key itself in case you want to make use of it you just need to call the error as it is.

myDict = {'key1':'value1'}

try:
    x1 = myDict['key1']
    x2 = myDict['key2'] 
except KeyError as missing_key:
    # Used as missing_key for readability purposes only
    print(f"Trying to access a <dict> with a missing key {missing_key}")

P.S. This was tested on Python version 3.8.12

Answered By: haddagart
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.