如何在Python中订购xml元素属性? [英] How to order xml element attributes in Python?
本文介绍了如何在Python中订购xml元素属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将xml文件解析为Python ElementTree时,属性的顺序混合了,因为Python将属性存储在字典中。
When parsing an xml file into a Python ElementTree the attributes' order is mixed up because Python stores the attributes in a dictionary.
如何更改顺序
推荐答案
您的自我回答就像您所说的那样冗长而繁琐。不必如此。如果(1)超过10个键(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
>>>
这篇关于如何在Python中订购xml元素属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文