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.

Easy Python 3.9+ Aug 9, 2026 Files & data 15 views 0 copies

Python code

25 lines
Python 3.9+
import 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

stdout
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

  1. Use `iter('book')` to parse all book elements regardless of nesting depth.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.