How to Parse XML Attributes into a Flat Dictionary in Python
Parses XML elements and attributes using ElementTree, building a flat dictionary keyed by element attributes.
Python code
25 linesimport xml.etree.ElementTree as ET
xml_data = """<root>
<book id="1" category="fiction" price="9.99">
<title>The Catcher</title>
</book>
<book id="2" category="nonfiction" price="12.50">
<title>Deep Learning</title>
</book>
</root>"""
def parse_xml_attributes(xml_string):
root = ET.fromstring(xml_string)
flat_dict = {}
for book in root.findall("book"):
book_id = book.get("id")
flat_dict[f"book_{book_id}_category"] = book.get("category")
flat_dict[f"book_{book_id}_price"] = book.get("price")
flat_dict[f"book_{book_id}_title"] = book.findtext("title")
return flat_dict
if __name__ == "__main__":
result = parse_xml_attributes(xml_data)
for key, value in sorted(result.items()):
print(f"{key}: {value}")
Output
book_1_category: fiction
book_1_price: 9.99
book_1_title: The Catcher
book_2_category: nonfiction
book_2_price: 12.50
book_2_title: Deep Learning
How it works
This approach uses xml.etree.ElementTree from the standard library to parse the XML string with ET.fromstring. The findall method locates all book elements, and get retrieves an attribute or returns None if missing, which is safe with .get(). The code builds a flat dictionary with keys combining the book id and field name, making it easy to access data without nested loops. Using findtext extracts the text content of the <title> child element directly.
Common mistakes
- Using `json.loads` on XML data, which expects JSON syntax.
- Assuming an attribute always exists without using `get` – `get` avoids `KeyError`.
- Not using the root element when searching, causing `findall` to return nothing.
Variations
- Use `iter('book')` to parse all book elements regardless of nesting depth.
- Use a list of dictionaries if you need to preserve the hierarchical structure.
Real-world use cases
- Converting config files from XML to a flat key-value store for easier logging.
- Transforming e-commerce product feeds, extracting attributes like price and category.
- Parsing API responses from legacy systems that still return XML into Python dicts for analysis.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.