Python How to Convert Dictionary to XML Easily
xml.etree.ElementTree module by creating XML elements from dictionary keys and values and then converting them to a string with ElementTree.tostring().Examples
How to Think About It
Algorithm
Code
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)
Dry Run
Let's trace the dictionary {"person": {"name": "Alice", "age": 30}} through the code
Create root element
root element named 'root' created
Process key 'person'
Create child element 'person' and detect value is a dictionary
Process nested keys
Create 'name' element with text 'Alice' and 'age' element with text '30' inside 'person'
| Element | Text |
|---|---|
| root | |
| person | |
| name | Alice |
| age | 30 |
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
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())
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)
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| xml.etree.ElementTree | O(n) | O(n) | Structured, safe XML generation |
| dicttoxml library | O(n) | O(n) | Quick setup with external package |
| Manual string building | O(n) | O(n) | Simple cases, but error-prone |