python - 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
这会引发有关它首先找到并中断执行的丢失键的错误。我想遍历整个字段集并在所有缺失的字段中引发错误。解决问题的最佳/有效方法是什么?
解决方案
使用 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
推荐阅读
- python - 如何使用 rpy2 使 arules.apriori 在 python 中工作
- c# - c#中的不可变结构
- c++ - 将函数作为参数传递时无效使用非静态成员函数
- ruby - 使用 shopify API 根据邮政编码脚本显示不同的运输区域
- spring-boot - Spring Boot 中的 DB 字段为空问题
- node.js - NestJS:使用 graphql 的 Passport LinkedIn 策略
- javascript - 使用 toISOString() 设置 CET 时区
- swift - Swift中的按位移位数据
- algorithm - 两个补码表示中的最大值
- .net - NET CLI 工具包含具有开发依赖项的 deps.json (GitVersion.MsBuild)