Monday, July 27, 2026
HomeLanguagesPython program to convert XML to Dictionary

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:

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) 

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 modules
import xmltodict
import pprint
  
# Open the file and read the contents
with open('example.xml', 'r', encoding='utf-8') as file:
    my_xml = file.read()
  
# Use xmltodict to parse and convert 
# the XML document
my_dict = xmltodict.parse(my_xml)
  
# Print the dictionary
pprint.pprint(my_dict, indent=2)


Output:

Example 2: Converting XML to dictionary

File Used:

Python3




# Import the required modules
import xmltodict
import pprint
  
# Open the file and read the contents
with open('example_2.xml', 'r', encoding='utf-8') as file:
    my_xml = file.read()
  
# Use xmltodict to parse and convert the 
# XML document
my_dict = xmltodict.parse(my_xml)
  
# Print the dictionary
pprint.pprint(my_dict, indent=2)


Output:

RELATED ARTICLES

Most Popular

Dominic
32520 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6903 POSTS0 COMMENTS
Nicole Veronica
12017 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12115 POSTS0 COMMENTS
Shaida Kate Naidoo
7023 POSTS0 COMMENTS
Ted Musemwa
7265 POSTS0 COMMENTS
Thapelo Manthata
6980 POSTS0 COMMENTS
Umr Jansen
6972 POSTS0 COMMENTS