检查嵌套的字典值? [英] Check nested dictionary values?
问题描述
对于大量的嵌套字典,我想检查它们是否包含键. 它们中的每个都可能有一个嵌套字典,也可能没有,所以如果我在所有这些字典中进行循环搜索,则会产生错误:
For a large list of nested dictionaries, I want to check if they contain or not a key. Each of them may or may not have one of the nested dictionaries, so if I loop this search through all of them raises an error:
for Dict1 in DictionariesList:
if "Dict4" in Dict1['Dict2']['Dict3']:
print "Yes"
到目前为止,我的解决方案是:
My solution so far is:
for Dict1 in DictionariesList:
if "Dict2" in Dict1:
if "Dict3" in Dict1['Dict2']:
if "Dict4" in Dict1['Dict2']['Dict3']:
print "Yes"
但这是一个令人头疼,丑陋的事情,而且可能对资源的利用不是很有效. 哪种方法可以正确地以第一种类型执行此操作,但是当字典不存在时又不会引发错误?
But this is a headache, ugly, and probably not very resources effective. Which would be the correct way to do this in the first type fashion, but without raising an error when the dictionary doesnt exist?
推荐答案
对空字典使用.get()
作为默认值:
Use .get()
with empty dictionaries as defaults:
if 'Dict4' in Dict1.get('Dict2', {}).get('Dict3', {}):
print "Yes"
如果不存在Dict2
键,则返回一个空字典,因此下一个链接的.get()
也将找不到Dict3
并依次返回一个空字典.然后in
测试返回False
.
If the Dict2
key is not present, an empty dictionary is returned, so the next chained .get()
will also not find Dict3
and return an empty dictionary in turn. The in
test then returns False
.
另一种方法是只捕获KeyError
:
try:
if 'Dict4' in Dict1['Dict2']['Dict3']:
print "Yes"
except KeyError:
print "Definitely no"
这篇关于检查嵌套的字典值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!