首页 > 解决方案 > Python,在字典中查找所有缺失的字段

问题描述

我编写了一个函数来验证是否所有字段都存在于 python 字典中。下面是代码。

def validate_participants(self, xml_line):
    try:
       participant_type = xml_line["participants"]["participant_type"]
       participant_role = xml_line["participants"]["participant_role"]
       participant_type = xml_line["participants"]["participant_type"]
       participant_id   = xml_line["participants"]["participant_id"]
       return True
     except KeyError as err:
       log.error(f'{err}')
       return False

这会引发有关它首先找到并中断执行的丢失键的错误。我想遍历整个字段集并在所有缺失的字段中引发错误。解决问题的最佳/有效方法是什么?

标签: pythonpython-3.xdictionaryexception

解决方案


使用 aset您可以获得差异,如果它是空的,则不会丢失键。

def validate_participants(self, xml_line):
    keys = {"participant_type", "participant_role", "participant_id"}
    return keys - xml_line["participants"].keys() or True

or True如果缺少键,则该方法返回缺失键的集合,否则返回 True

编辑:

要回答您的评论,无需使用尝试/除非您先检查:

def validate_participants(self, xml_line):
    keys = {"participant_type", "participant_role", "participant_id"}
    missing_keys = keys - xml_line["participants"].keys()

    if missing_keys:
        #return False or
        raise Value_Error(f"Missing values: {', '.join(missing_keys)}")

    #access the values/do work or
    return True

推荐阅读