我撰寫了一個函式來驗證 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
這會引發關于它首先找到的丟失鍵的錯誤并中斷執行。我想遍歷整個欄位集并在所有缺少的欄位中引發錯誤。解決問題的最佳/有效方法是什么?
uj5u.com熱心網友回復:
使用 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
編輯:
要回答您的評論,無需使用 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
uj5u.com熱心網友回復:
我會定義一組預期的鍵并減去實際的鍵:
expected_keys = {...}
actual_keys = xml_line["participants"].keys()
key_diff = expected_keys - actual_keys
現在創建一條key_diff關于缺少哪些鍵的訊息。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/333368.html
上一篇:noj->電子老鼠走迷宮
