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'
A Python KeyError is raised when you try to access an item in a dictionary that does not exist. You can fix this error by modifying your program to select an item from a dictionary that does exist. Or you can handle this error by checking if a key exists first.
Avoiding KeyError when accessing Dictionary Key We can avoid KeyError by using get() function to access the key value. If the key is missing, None is returned. We can also specify a default value to return when the key is missing.
If you want to get None if a value is missing you can use the dict 's . get method to return a value ( None by default) if the key is missing. To just check if a key has a value in a dict , use the in or not in keywords.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With