How to Convert Python XML to Dict ? : Step By Step Solution

How to Convert Python XML to Dict

We can convert Python XML to dict using xmltodict python module. We need to install xmltodict and parse the XML using parse() function.. In this article,  We will see step by step Implementation.


Python XML to dict Conversion-

Here are some steps which you need to follow for this conversion.

Step 1: Installation of xmltodict –

Use the below command on terminal or cmd for installing xmltodict python module.

pip install xmltodict


Step 2: Defining the XML

In this step, we will define the XML.


Sample XML
Sample XML


As we all know XML supports tags. Hence we have created a dummy XML. Now we parse it into a Python dict object.

Step 3: Parsing

In this step, We will parse the XML string into python dict object using parse() function of xmltodict library. It will return a orderDict as a return variable.

generated_dict = xmltodict.parse(sample_xml)

Complete Code –

Here is the complete code for all three above steps.

Convert Python XML to dict Google Colab

We have printed the value of “key1”. Which is the root of the XML tags. Let’s see the output for a better understanding.


Convert Python dict to XML –

It is just opposite to the above conversion. We can complete it using xmltodict also. Only In the place of parse function we will use unparse function. I think we should first see the implementation.

import xmltodict
sample_dict= {
  "key1" : {
    "inner_key1" : "value1",
    "inner_key2" :"value2"
print(xmltodict.unparse(sample_dict, pretty=True))

Here we have firstly created a python dict. Then we used unparse() with dict as a parameter. It will return the XML string to us.


dict to XML conversion


Conclusion –

As a developer, we all come to the situation where we need to convert the XML to dict and dict to XML. As per my understanding xmltodict is the best option for this. This tutorial is enough to introduce you to its capabilities. I hope we all on the same page now. Please provide your suggestions in the comment box. Especially if you know some better way for this.



Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Abhishek ( Chief Editor) , a data scientist with major expertise in NLP and Text Analytics. He has worked on various projects involving text data and have been able to achieve great results. He is currently manages, where he and his team share knowledge and help others learn more about data science.
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner