0
0
PythonHow-ToBeginner · 2 min read

Python How to Convert XML to Dictionary Easily

Use the xmltodict.parse() function to convert XML string to a Python dictionary, for example: import xmltodict; data_dict = xmltodict.parse(xml_string).
📋

Examples

Input<note><to>Alice</to><from>Bob</from></note>
Output{"note": {"to": "Alice", "from": "Bob"}}
Input<person><name>John</name><age>30</age></person>
Output{"person": {"name": "John", "age": "30"}}
Input<empty></empty>
Output{"empty": null}
🧠

How to Think About It

To convert XML to a dictionary, first read the XML as a string, then use a parser that understands XML structure and converts tags and nested elements into dictionary keys and values. This way, the hierarchical XML data becomes a nested Python dictionary.
📐

Algorithm

1
Get the XML data as a string.
2
Import an XML parsing library like xmltodict.
3
Use the library's parse function to convert the XML string to a dictionary.
4
Return or use the resulting dictionary.
💻

Code

python
import xmltodict

xml_string = '''<note><to>Alice</to><from>Bob</from></note>'''
data_dict = xmltodict.parse(xml_string)
print(data_dict)
Output
{'note': {'to': 'Alice', 'from': 'Bob'}}
🔍

Dry Run

Let's trace the example XML '<note><to>Alice</to><from>Bob</from></note>' through the code

1

Input XML string

AliceBob

2

Parse XML to dictionary

{'note': {'to': 'Alice', 'from': 'Bob'}}

3

Print dictionary

{'note': {'to': 'Alice', 'from': 'Bob'}}

StepActionResult
1Read XML stringAliceBob
2Parse XML{'note': {'to': 'Alice', 'from': 'Bob'}}
3Output dictionary{'note': {'to': 'Alice', 'from': 'Bob'}}
💡

Why This Works

Step 1: Parsing XML

The xmltodict.parse() function reads the XML string and converts tags into dictionary keys.

Step 2: Nested structure

Nested XML tags become nested dictionaries, preserving the XML hierarchy.

Step 3: Resulting dictionary

The output is a Python dictionary that you can use like any other dictionary.

🔄

Alternative Approaches

Using ElementTree
python
import xml.etree.ElementTree as ET

def etree_to_dict(elem):
    d = {elem.tag: {}}
    for child in elem:
        d[elem.tag].update(etree_to_dict(child))
    if not d[elem.tag]:
        d[elem.tag] = elem.text
    return d

xml_string = '<note><to>Alice</to><from>Bob</from></note>'
root = ET.fromstring(xml_string)
data_dict = etree_to_dict(root)
print(data_dict)
ElementTree is built-in but requires custom code to convert to dictionary; less straightforward than xmltodict.
Using minidom and manual parsing
python
from xml.dom.minidom import parseString

def dom_to_dict(node):
    d = {}
    if node.nodeType == node.TEXT_NODE:
        return node.data.strip()
    for child in node.childNodes:
        if child.nodeType == child.ELEMENT_NODE:
            d[child.tagName] = dom_to_dict(child)
    return d

xml_string = '<note><to>Alice</to><from>Bob</from></note>'
dom = parseString(xml_string)
data_dict = dom_to_dict(dom.documentElement)
print(data_dict)
minidom is also built-in but requires more manual work and is less convenient.

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

Time Complexity

Parsing XML requires reading each element once, so time grows linearly with XML size.

Space Complexity

The dictionary stores all XML data, so space grows linearly with input size.

Which Approach is Fastest?

xmltodict is optimized and simple, usually faster and easier than manual parsing with ElementTree or minidom.

ApproachTimeSpaceBest For
xmltodictO(n)O(n)Quick and easy XML to dict conversion
ElementTree with custom codeO(n)O(n)Built-in, more control but more code
minidom manual parsingO(n)O(n)Built-in, but verbose and complex
💡
Install xmltodict with pip install xmltodict for the easiest XML to dictionary conversion.
⚠️
Trying to parse XML with string methods instead of using a proper XML parser leads to errors and incorrect results.