1

I have a line of code

attributes_dict["data_properties"] = {
    prop: getattr(ontology_node, prop) for prop in data_properties
}

However, not every ontology_node will have all of the properties, so I'd like to do something similar to the following

attributes_dict["data_properties"] = {
    prop: getattr(ontology_node, prop) for prop in data_properties if getattr(onotology_node, prop)
}

Unfortunately this does not work properly. Is there a way to check if that exists within the ontology_node within a dict comprehension like the above?

Of course I can manually do this, but I would like to use a dict comprehension if possible.

Thank you

Sean Payne
  • 1,625
  • 1
  • 8
  • 20

1 Answers1

2

hasattr should do the work

attributes_dict["data_properties"] = {
    prop: getattr(ontology_node, prop) for prop in data_properties if hasattr(onotology_node, prop)
}

PS: prop should be of a str type

Roman Zh.
  • 985
  • 2
  • 6
  • 20
  • 1
    For your editification it's also possible to give `getattr` a third value, which is a *default*, returned in case the attribute is not present on the object. This doesn't seem too useful here unless you use an assignment hack but in other situations it is quite convenient. – Masklinn Nov 20 '20 at 13:29