【问题标题】:Python: how to solve KeyError for non existing dictionary key? [duplicate]Python:如何解决不存在的字典键的 KeyError? [复制]
【发布时间】:2021-07-28 18:38:58
【问题描述】:

如果嵌套过滤器中的键存在,我正在尝试附加到 dict。但即使密钥不存在,看起来代码也会被执行,因为它向我显示 KeyError 错误。因此,如果 useValueFromAnotherField 不在我的字典中,我不希望执行此代码。我该如何解决?

KeyError: 'useValueFromAnotherField'

字典

${FILTERS}=    {'Manager ID': {"operatorId": 'equal to',  "targetValue":'test',"dataType": 'Text', "targetType": 'targetText'}, 
'Terminated': {"operatorId": 'equl to', "targetValue": 'True', "dataType": 'Boolean', "targetType": 'targetBoolean'}}```

code
def filter_value_from_another_field(self, pipeline, new_filter, source_field_id, filter_to_add):
    for source_field in filter_to_add.keys():
        if filter_to_add[source_field]["useValueFromAnotherField"]:
            for value in self.ssi_get_value_from_another_field(pipeline, source_field_id).json_path("$.data"):
                if value["descriptor"] == filter_to_add[source_field]["useValueFromAnotherField"]:
                    new_filter["useValueFromAnotherField"] = value
                    return new_filter

【问题讨论】:

  • 使用if "someKey" in someDict: 检查是否存在密钥。

标签: python dictionary nested


【解决方案1】:

正如 John 所提到的,您可以使用简单的检查来检查字典 filter_to_add[source_field] 中是否存在密钥 useValueFromAnotherField,解决方案应如下所示:

def filter_value_from_another_field(self, pipeline, new_filter, source_field_id, filter_to_add):
    for source_field in filter_to_add.keys():
        if "useValueFromAnotherField" in filter_to_add[source_field]:
            if filter_to_add[source_field]["useValueFromAnotherField"]:
                for value in self.ssi_get_value_from_another_field(pipeline, source_field_id).json_path("$.data"):
                    if value["descriptor"] == filter_to_add[source_field]["useValueFromAnotherField"]:
                        new_filter["useValueFromAnotherField"] = value
                        return new_filter

【讨论】:

  • 是的,它以这种方式工作。谢谢
猜你喜欢
  • 1970-01-01
  • 2021-07-15
  • 2016-12-27
  • 2016-05-25
  • 1970-01-01
  • 1970-01-01
  • 2021-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多