Convert a Dictionary to XML Format in Python

Converting a dictionary to XML format allows you to represent structured data in a hierarchical format that can be easily shared or processed by other systems. In this blog post, we will explore how to convert a dictionary to XML format in Python.

Method: Using the xml.etree.ElementTree module

import xml.etree.ElementTree as ET

def dict_to_xml(dictionary, root_name):
    root = ET.Element(root_name)
    for key, value in dictionary.items():
        if isinstance(value, dict):
            child = dict_to_xml(value, key)
            root.append(child)
        else:
            child = ET.Element(key)
            child.text = str(value)
            root.append(child)
    return root

my_dict = {"person": {"name": "Alice", "age": 25, "country": "USA"}}

root = dict_to_xml(my_dict, "data")
tree = ET.ElementTree(root)
tree.write("output.xml")

print("XML file created.")

Output:

XML file created.