write a python dictionary in xml file in python

To write a Python dictionary to an XML file, you can use the built-in XML library xml.etree.ElementTree. Here's an example code block:

main.py
import xml.etree.ElementTree as ET

def dict_to_xml(dict_obj, root_elem):
    for key, val in dict_obj.items():
        if isinstance(val, dict):
            elem = ET.Element(key)
            root_elem.append(elem)
            dict_to_xml(val, elem)
        else:
            ET.SubElement(root_elem, key).text = str(val)

my_dict = {"person": {"name": "John", "age": 25, "gender": "male"}}

root = ET.Element("root")
dict_to_xml(my_dict, root)

xml_str = ET.tostring(root, encoding="unicode")

with open("dictionary.xml", "w") as f:
    f.write(xml_str)
556 chars
21 lines

In this example, dict_to_xml() is a recursive function that converts a dictionary object to an ElementTree object. We pass the top-level dictionary object and the root element of the XML document to this function. For each key-value pair in the dictionary, we create an XML element with the key as the tag name and the value as the element text. If the value is another dictionary object, we recursively call dict_to_xml() to add its elements to the current element.

After converting the dictionary to an XML document, we use the tostring() method of the ElementTree object to generate an XML string, and write it to a file using the open() function.

gistlibby LogSnag