Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

like image 324
yossi Avatar asked Dec 06 '12 14:12

yossi


People also ask

How do you find the key error in Python?

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.

How do I bypass KeyError in Python?

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.

How do you get a value from a dictionary in a way that doesn't raise an exception for missing keys in Python?

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.

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.


2 Answers

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

like image 52
Ashwini Chaudhary Avatar answered Oct 01 '22 11:10

Ashwini Chaudhary


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 
like image 34
Holger Avatar answered Oct 01 '22 11:10

Holger