[英]Checking if getattr exists within a dictionary comprehension in Python3
我有一行代碼
attributes_dict["data_properties"] = {
prop: getattr(ontology_node, prop) for prop in data_properties
}
但是,並非每個 ontology_node 都具有所有屬性,因此我想做類似於以下內容的操作
attributes_dict["data_properties"] = {
prop: getattr(ontology_node, prop) for prop in data_properties if getattr(onotology_node, prop)
}
不幸的是,這不能正常工作。 有沒有辦法檢查它是否存在於像上面這樣的字典理解中的 ontology_node 中?
當然,我可以手動執行此操作,但如果可能,我想使用 dict 理解。
謝謝
hasattr應該做的工作
attributes_dict["data_properties"] = {
prop: getattr(ontology_node, prop) for prop in data_properties if hasattr(onotology_node, prop)
}
PS: prop
應該是str
類型
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.