python - 访问嵌套字典,它使用 get 方法和 for 循环在 python 中保存空条目
问题描述
假设您有以下字典:
configuration = {'key1':{'thresholds': {"orange": 3.0, "red": 5.0}, {'plotSettings': {'yaxisscale': 'linear', "ylabel": "bar", 'ymin': 0}}, 'key2': {'thresholds': {"orange": 3.0, "red": 5.0}, 'plotSettings': {
'yaxisscale': 'linear', "ylabel": "bar", 'ymin': 0}}, 'key3': {'thresholds': {"orange": 3.0, "red": 5.0}, 'plotSettings': {'yaxisscale': 'linear', "ylabel": "bar", 'ymin': 0}}}
一切都很好
thresholds = {key:configuration[key]['thresholds'] for key in configuration}
但是,如果某些键不包含阈值部分,我会得到 keyError。
configuration = {'key1':{'thresholds': {"orange": 3.0, "red": 5.0}, {'plotSettings': {'yaxisscale': 'linear', "ylabel": "bar", 'ymin': 0}}, 'key2': {'thresholds': {"orange": 3.0, "red": 5.0}, 'plotSettings': {
'yaxisscale': 'linear', "ylabel": "bar", 'ymin': 0}}, 'key3': {'thresholds': {"orange": 3.0, "red": 5.0}, 'plotSettings': {'yaxisscale': 'linear', "ylabel": "bar", 'ymin': 0}}}
thresholds = {key:configuration[key]['thresholds'] for key in configuration}
经常描述的 keyError 来了。
我试图以这种方式解决它:
thresholds = configuration.get(key, {}).get(
'thresholds' for key in configuration)
但当时不知道密钥。你会怎么解决。
解决方案
一种选择是添加检查是否'thresholds'
存在
thresholds = {key: configuration[key]['thresholds'] for key in configuration if 'thresholds' in configuration[key]}
# {'key2': {'orange': 3.0, 'red': 5.0}, 'key3': {'orange': 3.0, 'red': 5.0}}
使用get()
你可以做类似的事情
thresholds = {key: configuration[key].get('thresholds', {}) for key in configuration}
# {'key1': {}, 'key2': {'orange': 3.0, 'red': 5.0}, 'key3': {'orange': 3.0, 'red': 5.0}}
但是,这将在thresholds
.
推荐阅读
- amazon-web-services - 以编程方式跨不同帐户访问 cloudwatch
- c# - 无法更改 Xamarin Forms v4.1 中的工具栏图标
- java - 如何制作这个菜单
- java - 从线程调用 repaint()
- c# - C# AES-GCM 分成几部分
- java - 非常令人困惑的 Java.lang.RuntimeException: java.io.FileNotFoundException:
- android - Android Q (10) 请求访问所有存储的权限。范围存储
- docker - xwiki (docker) 在 Synology 上安装 500 – 内部服务器错误
- google-apps-script - 成功运行后谷歌表格自定义功能错误“未知功能”
- javascript - 如何在 Windows 中正确杀死由 node.js/electron 生成的 child_process?