在Python中处理多个KeyErrors

Handling multiple KeyErrors in Python

当我尝试捕获KeyError两次时出现此错误。 python中有什么阻止你试图捕获相同的错误两次?

1
2
3
4
5
6
7
$ ./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'

简化代码如下

1
2
3
4
5
6
7
8
9
10
11
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'


我会用一个简单的for循环来做到这一点:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> 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'

如果你想在一行中做到这一点:

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


你需要额外的尝试......除了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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'