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"
我目前的解决方案是:
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"
这篇关于检查嵌套字典值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查嵌套字典值?
基础教程推荐
- 修改列表中的数据帧不起作用 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 包装空间模型 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
