python 38 lines · 9 steps

Converting nested dicts to XML in Python

A recursive builder turns dictionaries, lists, and scalars into an ElementTree structure, then serializes it to formatted XML.

Explained by highlit
1from xml.etree import ElementTree as ET
2from xml.dom import minidom
3 
4 
5def dict_to_element(tag, value):
6 element = ET.Element(tag)
7 
8 if isinstance(value, dict):
9 attrs = value.pop("@attributes", None)
10 if isinstance(attrs, dict):
11 for name, attr_value in attrs.items():
12 element.set(name, str(attr_value))
13 
14 text = value.pop("#text", None)
15 if text is not None:
16 element.text = str(text)
17 
18 for key, child_value in value.items():
19 if isinstance(child_value, list):
20 for item in child_value:
21 element.append(dict_to_element(key, item))
22 else:
23 element.append(dict_to_element(key, child_value))
24 elif isinstance(value, (list, tuple)):
25 for item in value:
26 element.append(dict_to_element("item", item))
27 elif value is not None:
28 element.text = str(value)
29 
30 return element
31 
32 
33def dict_to_xml(root_tag, data, pretty=True):
34 root = dict_to_element(root_tag, data)
35 rough = ET.tostring(root, encoding="unicode")
36 if not pretty:
37 return rough
38 return minidom.parseString(rough).toprettyxml(indent=" ")
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Recursion mirrors the shape of nested data, letting one function handle arbitrary depth.
  2. 2Reserved key conventions like @attributes and #text let a flat dict encode XML's attribute-and-text model.
  3. 3Building a tree first and serializing last cleanly separates structure from formatting concerns.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Converting nested dicts to XML in Python — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code