首页 > 解决方案 > 访问嵌套字典,它使用 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)

但当时不知道密钥。你会怎么解决。

标签: pythondictionary

解决方案


一种选择是添加检查是否'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.


推荐阅读