write dictionary in xml file in python

One way to write a dictionary to an XML file in Python is by using the ElementTree module. Here is an example code snippet:

main.py
import xml.etree.ElementTree as ET

my_dict = {"name": "John", "age": 30, "gender": "Male"}

root = ET.Element("data")
for key, value in my_dict.items():
    child = ET.Element(key)
    child.text = str(value)
    root.append(child)

tree = ET.ElementTree(root)
tree.write("my_dict.xml")
288 chars
13 lines

In the above code, we first define a dictionary called my_dict with some key-value pairs. We then create a root element called "data" using ET.Element(). Next, we iterate through the dictionary using a for loop to create child elements for each key-value pair. For each child element, we set the element name as the key and set its text content as the string representation of the value. Finally, we create an ElementTree instance using the root element and write it to an XML file called "my_dict.xml" using tree.write().

gistlibby LogSnag