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.py288 chars13 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