Open In App
Related Articles

Turning a Dictionary into XML in Python

Improve Article
Save Article
Like Article

XML stands for Extensible Markup Language. XML was designed to be self-descriptive and to store and transport data. XML tags are used to identify, store and organize the data. The basic building block of an XML document is defined by tags. An element has a beginning tag and an ending tag. All elements in an XML are contained in an outermost element called as the root element.



In the above example, geeksforgeeks is the root element and <course>, <price>, <price> are the elements.

Now, let’s see how to Turn a Dictionary into XML:
For turning a Dictionary into XML in Python we will use xml.etree.ElementTree library. The xml.etree.ElementTree library is usually used for parsing and also utilized in creating XML documents. The ElementTree class is employed to wrap a component structure and convert it from and to XML. The result of this conversion is an Element. For I/O, it’s easy to convert this to a byte string using the tostring() function in xml.etree.ElementTree.

xml.etree.ElementTree.Element() Class:

This Element class defines the Element interface, and provides a reference implementation of this interface. 

Syntax: Element(tag, attrib = {}, **extra) 


  • tag: This is a string that identify what kind of data this element represents.
  • attrib: this is an optional dictionary, containing element attributes.
  • **extra: This contains additional attributes, given as keyword arguments.

Return: Element object

xml.etree.ElementTree.tostring() Function:

This function Generates a string representation of an XML element. 

Syntax: tostring(element)

Parameter: XML element

Return: string representation of an XML element

ElementObject.set() Method:

This method Set the attribute key on the element to value. 

Syntax: set(key, value) 


  • key: represent the attribute.
  • value: represent value of attribute.

Return: None

Now, let’s see the python program for Turning a Dictionary into XML:


# import Element class, tostring function
# from xml.etree.ElementTree library
from xml.etree.ElementTree import Element,tostring
# define a function to
# convert a simple dictionary
# of key/value pairs into XML
def dict_to_xml(tag, d):
    elem = Element(tag)
    for key, val in d.items():
        # create an Element
        # class object
        child = Element(key)
        child.text = str(val)
    return elem
# Driver Program
s = { 'name': 'geeksforgeeks',
     'city': 'noida', 'stock': 920 }
# e stores the element instance
e = dict_to_xml('company', s)
# Element instance is different
# every time you run the code
# converting into a byte string
# We can attach attributes
# to an element using
# set() method


<Element ‘company’ at 0x7f411a9bd048> 
b'<company _id=”1000″><name>geeksforgeeks</name><city>noida</city><stock>920</stock></company>’ 

Last Updated : 01 Sep, 2021
Like Article
Save Article
Similar Reads
Related Tutorials