Robert Carter Mills
Robert Carter Mills

Reputation: 793

How to order xml element attributes in Python?

When parsing an xml file into a Python ElementTree the attributes' order is mixed up because Python stores the attributes in a dictionary.

How can I change the order of the attributes in the dictionary?

Upvotes: 2

Views: 4576

Answers (4)

Robert Carter Mills
Robert Carter Mills

Reputation: 793

You can not change the order of attributes internally in the dictionary. This is impossible unless you do some fancy hacking.

The solution therefore, is to manually access the attributes in the order you want them, or create a list of the keys/items and sort that the way you want.

Upvotes: 0

John Machin
John Machin

Reputation: 83032

Your self-answer is as you said long and cumbersome. It doesn't need to be. Also it will fail if (1) there are more than 10 keys (2) a dict has fewer keys than than expected.

Try this; it's much simpler:

>>> ordered_keys = ('z', 'y', 'e', 'x', 'w') # possible keys, in desired order

Note: the above line is all the setup that is required.

>>> dic = {'z':'a', 'y':'b', 'x':'c', 'w':'d'} # actual contents of a dictionary
>>> for k in ordered_keys:
...     if k in dic: # avoid trouble if a key is missing
...         print k, dic[k]
...
z a
y b
x c
w d
>>>

Upvotes: 2

phihag
phihag

Reputation: 288280

XML attributes are by definition unordered1, compare paragraph 3.1 of the official standard.

1Technically, attribute lists are ordered, but the order is not significant, i.e. writers, transformers and parsers are free to switch it around as they like.

Upvotes: 6

user2665694
user2665694

Reputation:

XML does not define any ordering of attributes of a node. So the behavior is fine. If you make assumptions about the ordering of attributes then your assumptions are wrong. There is no ordering and you must not expect any kind of attribute ordering. So your question is invalid.

Upvotes: 0

Related Questions