0
0
PythonHow-ToBeginner · 2 min read

Python How to Convert Dictionary to XML Easily

You can convert a dictionary to XML in Python using the xml.etree.ElementTree module by creating XML elements from dictionary keys and values and then converting them to a string with ElementTree.tostring().
📋

Examples

Input{"name": "John"}
Output<root><name>John</name></root>
Input{"person": {"name": "Alice", "age": 30}}
Output<root><person><name>Alice</name><age>30</age></person></root>
Input{}
Output<root />
🧠

How to Think About It

To convert a dictionary to XML, think of each key as an XML tag and its value as the tag's content. If the value is another dictionary, create nested tags. Use a root tag to wrap the entire XML structure. This way, the dictionary structure maps naturally to XML elements.
📐

Algorithm

1
Create a root XML element to hold all data.
2
For each key-value pair in the dictionary:
3
If the value is a dictionary, recursively create child elements.
4
If the value is a simple type, create an element with the key as tag and value as text.
5
Convert the root element tree to a string and return it.
💻

Code

python
import xml.etree.ElementTree as ET

def dict_to_xml(tag, d):
    elem = ET.Element(tag)
    for key, val in d.items():
        if isinstance(val, dict):
            child = dict_to_xml(key, val)
        else:
            child = ET.Element(key)
            child.text = str(val)
        elem.append(child)
    return elem

sample_dict = {"person": {"name": "Alice", "age": 30}}
root = dict_to_xml('root', sample_dict)
xml_str = ET.tostring(root, encoding='unicode')
print(xml_str)
Output
<root><person><name>Alice</name><age>30</age></person></root>
🔍

Dry Run

Let's trace the dictionary {"person": {"name": "Alice", "age": 30}} through the code

1

Create root element

root element named 'root' created

2

Process key 'person'

Create child element 'person' and detect value is a dictionary

3

Process nested keys

Create 'name' element with text 'Alice' and 'age' element with text '30' inside 'person'

ElementText
root
person
nameAlice
age30
💡

Why This Works

Step 1: Mapping keys to tags

Each dictionary key becomes an XML tag, which organizes data clearly.

Step 2: Handling nested dictionaries

If a value is a dictionary, recursion creates nested XML elements to preserve structure.

Step 3: Converting to string

The ElementTree module converts the XML element tree into a string for output or saving.

🔄

Alternative Approaches

Using dicttoxml library
python
from dicttoxml import dicttoxml
sample_dict = {"person": {"name": "Alice", "age": 30}}
xml_bytes = dicttoxml(sample_dict, custom_root='root', attr_type=False)
print(xml_bytes.decode())
This method is simpler and handles many cases automatically but requires installing an external package.
Manual string building
python
def dict_to_xml_str(d):
    xml = ''
    for k, v in d.items():
        if isinstance(v, dict):
            xml += f'<{k}>' + dict_to_xml_str(v) + f'</{k}>'
        else:
            xml += f'<{k}>{v}</{k}>'
    return xml

sample_dict = {"person": {"name": "Alice", "age": 30}}
xml_str = '<root>' + dict_to_xml_str(sample_dict) + '</root>'
print(xml_str)
This approach is simple but error-prone and does not handle special XML characters or attributes.

Complexity: O(n) time, O(n) space

Time Complexity

The code visits each key-value pair once, so time grows linearly with dictionary size.

Space Complexity

The XML tree and string output require space proportional to the input dictionary size.

Which Approach is Fastest?

Using xml.etree.ElementTree is efficient and safe; dicttoxml is convenient but adds dependency; manual string building is fastest but risky.

ApproachTimeSpaceBest For
xml.etree.ElementTreeO(n)O(n)Structured, safe XML generation
dicttoxml libraryO(n)O(n)Quick setup with external package
Manual string buildingO(n)O(n)Simple cases, but error-prone
💡
Use the built-in xml.etree.ElementTree module for safe and structured XML creation from dictionaries.
⚠️
Beginners often forget to handle nested dictionaries recursively, resulting in incomplete XML.