2

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?

1
  • oops. This question had been asked already: link Commented Mar 22, 2011 at 4:22

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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
>>>

1 Comment

Thanks John! Yeah, only a day later and I started seeing many flaws in my noobish code. :\
0

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.

Comments

0

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.

1 Comment

"you will see that the order is lost" -- a dictionary has no order to lose.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.