gpt4 book ai didi

python - 处理 Python 中的多个 KeyError

转载 作者:行者123 更新时间:2023-12-01 05:06:24 28 4
gpt4 key购买 nike

当我两次 try catch KeyError 时,出现此错误。 python 中是否有任何东西可以阻止您两次 try catch 相同的错误?

$ ./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'

简化代码如下

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 循环来做到这一点:

>>> 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)

关于python - 处理 Python 中的多个 KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24931259/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com