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"
这篇关于检查嵌套字典值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查嵌套字典值?
基础教程推荐
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
