Search code examples
pythonxmldictionaryxml-parsinglxml.objectify

Creating python objectify Element and then adding attributes


I am trying to serialize a python class named Origin, containing a dictionary as an attribute, into an xml with lxml objectify. This dictionary is initialized with the value "default" for each key.

class Origin:
    def __init__(self):
        dict = {"A":"default", "B":"default" ...} // my dictionnary has 6 keys actually

The dictionary is filled by first parsing a XML. Not every key is filled. For exemple: dict = {A:"hello", B:"default" ...}

I want to create my Origin XML Element with my dictionary as attribute but I don't want to have the "default" keys.

My solution is to have nested if:

ìf(self.dict["A"] != "default"):
    if(self.dict["B"] != "default"):
   ...
        objectify.Element("Origin", A=self.dict["A"], B=self.dict["B"]...)

But it's an ugly and non practical solution if you have more than one or two keys.

Is there a way to first create my Element origin = objectify.Element("Origin") and then add my dictionary keys' if there are different from "default"?

Something more dynamic, like

for key in self.dict:
    if(self.dict[key] != "default"):
        origin.addAttribute(key=self.dict[key])

Thank you


Solution

  • I would filter the dictionary to only the values that are not "default".

    The dict comprehension feature is a big help here.

    Example:

    data = {
        "A": "foo",
        "B": "default",
        "C": "bar",
    }
    
    data = {key: value for key, value in data.items() if value != "default"}
    print(data)
    

    Output:

    {'A': 'foo', 'C': 'bar'}