Search code examples
pythonpython-3.xdictionarydictionary-comprehensiongetattr

Checking if getattr exists within a dictionary comprehension in Python3


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


Solution

  • 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