nev
nev

Reputation: 19

Handling multiple KeyErrors in Python

I get this error when I try to catch a KeyError twice. Is there anything in python which prevents you trying to catch the same error twice?

$ ./scratch.py
try getting a
can't get a try getting b
Traceback (most recent call last):
  File "./scratch.py", line 13, in <module>
    print dict['b']
KeyError: 'b'

The simplified code is below

dict={}
dict['c'] = '3'

try:
        print 'try getting a'
        print dict['a']
except KeyError:
        print 'can\'t get a try getting b'
        print dict['b']
except:
        print 'can\'t get a or b'

Upvotes: 1

Views: 1126

Answers (2)

wim
wim

Reputation: 362647

I would do this with a simple for loop:

>>> d = {'c': 1}
>>> keys = ['a', 'b', 'c']
>>> for key in keys:
...     try:
...         value = d[key]
...         break
...     except KeyError:
...         pass
... else:
...     raise KeyError('not any of keys in dict')
... 
>>> value
1
>>> key
'c'

If you want to do it in one line:

key, value = next((k, d[k]) for k in keys if k in d)

Upvotes: 2

Anthony Kong
Anthony Kong

Reputation: 40644

You need an extra try...except:

dict={}
dict['c'] = '3'

try:
        print 'try getting a'
        print dict['a']
except KeyError:
        print 'can\'t get a try getting b'
        try:
            print dict['b']
        except KeyError as e:
            print "Got another exception", e
except:
        print 'can\'t get a or b'

Upvotes: 0

Related Questions