XML elements support attributes. You can create them directly in the Element factory.
>>> root = etree.Element("root", interesting="totally")>>> etree.tostring(root)b'<root interesting="totally"/>'
Attribute is a name-Value Pair without sequence, so a convenient way to process them is through the element interface of the class dictionary.
>>> print(root.get("interesting"))totally>>> print(root.get("hello"))None>>> root.set("hello", "Huhu")>>> print(root.get("hello"))Huhu>>> etree.tostring(root)b'<root interesting="totally" hello="Huhu"/>'>>> sorted(root.keys())['hello', 'interesting']>>> for name, value in sorted(root.items()):... print('%s = %r' % (name, value))hello = 'Huhu'interesting = 'totally'
In other cases, for example, you want to search for elements or access an object of a real dictionary class. You can use attrib attributes
>>> attributes = root.attrib>>> print(attributes["interesting"])totally>>> print(attributes.get("no-such-attribute"))None>>> attributes["hello"] = "Guten Tag">>> print(attributes["hello"])Guten Tag>>> print(root.get("hello"))Guten Tag
Note that attrib is a class dictionary object supported by the Element itself. This means that any change to Elements will be reflected to attrib, and vice versa. This also means that the XML tree remains in the memory as long as the attrib of one of Elements is in use. To obtain the attributes of an independent image, instead of relying on the XML tree, copy it to the dictionary.
>>> d = dict(root.attrib)>>> sorted(d.items())[('hello', 'Guten Tag'), ('interesting', 'totally')]