我编写了一个函数来验证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
这会引发一个关于它首先找到的丢失键的错误,并中断执行。我想遍历整个字段集,并对所有缺失的字段抛出错误。解决这个问题最好/最有效的方法是什么?
使用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
编辑:
要回答您的评论,不需要使用try/,除非您先检查:
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
我将定义一组期望的键并减去实际的键:
expected_keys = {...}
actual_keys = xml_line["participants"].keys()
key_diff = expected_keys - actual_keys
现在从key_diff
创建一个消息,关于哪些键丢失。