如何使用这样的:
但是,使用collections.OrderedDict(),而不是简单的字典,以维持秩序。你有一本字典之后,这是非常,非常容易得到和格式化从它的文字:
使用@Colt 45的解决方案:
import xml.etree.ElementTree
import collections
s = """\
| Height | Width | Depth |
|---|---|---|
| 10 | 12 | 5 |
| 0 | 3 | 678 |
| 5 | 3 | 4 |
"""
table = xml.etree.ElementTree.XML(s)
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
values = [col.text for col in row]
for key, value in collections.OrderedDict(zip(headers, values)).iteritems():
print key, value
输出:
Height 10
Width 12
Depth 5
Height 0
Width 3
Depth 678
Height 5
Width 3
Depth 4
本文介绍了一种利用Python中的collections.OrderedDict来保持XML数据转换为字典后的顺序的方法。通过实例演示了如何解析XML字符串,将其转换为有序字典,并按顺序打印出键值对。
1071

被折叠的 条评论
为什么被折叠?



