【问题标题】:Python, find all missing fields in a dictionaryPython,在字典中查找所有缺失的字段
【发布时间】:2021-11-25 04:22:20
【问题描述】:

我编写了一个函数来验证是否所有字段都存在于 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

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

【问题讨论】:

  • 创建一个包含所有必填字段的集合。制作一个包含所有实际字段的集合。第一组减去第二组,就是所有缺失的字段。
  • 首先检查每个键是否存在于字典中。 if key in xml_line.keys()
  • 如果 participants 键不存在,您希望/期望什么行为?

标签: python python-3.x dictionary exception


【解决方案1】:

使用set 可以获得差异,如果它为空,则不会丢失键。

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

【讨论】:

  • 谢谢!我将如何在尝试中包装它,除了?为了测试而询问。
  • 没有必要进行尝试,除非..在访问值之前使用集合中差异的结果作为您的检查。如果差异中有值,您可以抛出错误。
【解决方案2】:

我会定义一组预期的键并减去实际的键:

expected_keys = {...}
actual_keys = xml_line["participants"].keys()
key_diff = expected_keys - actual_keys

现在创建来自key_diff 的消息,说明缺少哪些密钥。

【讨论】:

  • 谢谢!我将如何在尝试中包装它,除了?为了测试而询问。
  • @user8211795 我不确定try...except 与测试有什么关系。如果您遇到新问题,您应该发布一个新问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多