How to Convert a Dictionary into XML in Python



Python


In this article, we show how to convert a dictionary into XML in Python.

So in Python, dictionary are composed of items that are key-value pairs. This could be anything such as the name of a student, a class subject, and a grade.

Let's go over an example of the following dictionary shown below.



The dictionary above lists the headquarters location for various tech companies.

How can we now turn this dictionary above into an XML document where these key-value pairs are XML elements?

We use the xml.etree.ElementTree library in Python, which can be used to create XML documents. This same library is also commonly used to parse XML documents.

The code to do this is shown below.



After this code is run, we get the following output shown below.



So you can see that each of the items of the dictionary were converted into XML elements. You can then copy and paste this code into an XML document or use Python code to take the variable, xmldoc, and create an XML document.

So let us know break down the code line by line.

So the first thing we have to do is import Element from the xml.etree.ElementTree library.

Elements allows us to create XML elements. In this case, we create XML elements from dictionary items. The key of the dictionary, in this case, the name of the companies (Apple, Google, Amazon, Facebook) are the element name. The value of the dictionary, in this case, the headquarter locations (Cupertino, CA, Mountain View, CA, Seattle, WA, Menlo Park, CA) are the text of the elements (the text appears in between the elements).

We create a variable, elemn, which represents the entire overcasing element. In this case, it is 'Company Headquarters'.

We then have a for loop to loop through all the key-value pairs in the dictionary.

The variable, child, will hold each individual element and will be asigned the name of the key (the company name).

We then use the text attribute to assign the text in between each child element to the value of the dictionary.

Then we simply append each child element to the parent element.

We have our dictionary, dict1, which lists companies and their headquarters.

We then create another variable, xmldoc, which calls the function, dict_to_xml(). Into this function, we pass in the name of the element, in this case, 'Company Headquarters' and the dictionary, dict1.

We then create another variable, xmldoc_print, which uses the tostring() function to render and make displayable the XML elements now created from the Python dictionary. Remember that this tostring has to be imported from the xml.etree.ElementTree library, which we did in the second line of code.

We then print out the variable, which shows the XML elements.

So this is how we can convert a dictionary into XML elements in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...