对于嵌套字典的大列表,我想检查它们是否包含键。 它们中的每一个都可能有或没有一个嵌套字典,因此,如果我在所有这些字典中循环此搜索,将引发一个错误:
for Dict1 in DictionariesList:
if "Dict4" in Dict1['Dict2']['Dict3']:
print "Yes"
到目前为止,我的解决方案是:
for Dict1 in DictionariesList:
if "Dict2" in Dict1:
if "Dict3" in Dict1['Dict2']:
if "Dict4" in Dict1['Dict2']['Dict3']:
print "Yes"
但这是一个头痛,丑陋,可能不是很有效的资源。 在第一种类型的方式下,哪种方法是正确的,但是在字典不存在时不会产生错误?
尝试/排除块怎么样:
使用
.get()
和空字典作为默认值:如果
Dict2
键不存在,则返回空字典,因此下一个链接的.get()
也将找不到Dict3
,并依次返回空字典。然后,in
测试返回False
。另一种方法是只捕获
KeyError
:以下是任意键数的一般化:
基于Python: Change values in dict of nested dicts using items in a list。
相关问题 更多 >
编程相关推荐