Python program to convert XML to Dictionary
In this article, we will discuss how to convert an XML to a dictionary using Python.
Modules Used
- xmltodict: It is a Python module that makes working with XML feel like you are working with [JSON]. Run the following command in the terminal to install the module.
Syntax:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
pip install xmltodict
- pprint: The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a well-formatted and more readable way.
Approach
- Import necessary module to working space.
- Open the XML File in Read-only mode and read the contents using file.read() and store it in a variable.
Syntax:
with open('filename', 'r', encoding='utf-8') as file:
my_xml = file.read()- Use xmltodict.parse() to parse the content from the variable and convert it into Dictionary.
Syntax :
xmltodict.parse(xml_input, encoding=’utf-8′, expat=expat, process_namespaces=False, namespace_separator=’:’, **kwargs)
- Use pprint(pretty print) to print the dictionary in well-formatted and readable way.
Syntax :
pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True)
Example: Converting XML to dictionary
File Used:

Python3
# Import the required modulesimport xmltodictimport pprint # Open the file and read the contentswith open('example.xml', 'r', encoding='utf-8') as file: my_xml = file.read() # Use xmltodict to parse and convert # the XML documentmy_dict = xmltodict.parse(my_xml) # Print the dictionarypprint.pprint(my_dict, indent=2) |
Output:

Example 2: Converting XML to dictionary
File Used:

Python3
# Import the required modulesimport xmltodictimport pprint # Open the file and read the contentswith open('example_2.xml', 'r', encoding='utf-8') as file: my_xml = file.read() # Use xmltodict to parse and convert the # XML documentmy_dict = xmltodict.parse(my_xml) # Print the dictionarypprint.pprint(my_dict, indent=2) |
Output:


