我有一个从数据库中的两个字段读取的值字典:字符串字段和数字字段.字符串字段是唯一的,因此这是字典的键.
我可以对键进行排序,但是如何根据值进行排序?
注意:我已阅读Stack Overflow问题如何按Python中字典的值对字典列表进行排序?并且可能可以更改我的代码以获得字典列表,但由于我不需要字典列表,我想知道是否有更简单的解决方案.
我有以下函数,它将XML文件解析为字典.
不幸的是,由于Python字典没有排序,我无法按照我的意愿循环遍历节点.
如何更改此值以便输出一个有序字典,该字典反映了使用'for'循环时节点的原始顺序.
def simplexml_load_file(file):
import collections
from lxml import etree
tree = etree.parse(file)
root = tree.getroot()
def xml_to_item(el):
item = None
if el.text:
item = el.text
child_dicts = collections.defaultdict(list)
for child in el.getchildren():
child_dicts[child.tag].append(xml_to_item(child))
return dict(child_dicts) or item
def xml_to_dict(el):
return {el.tag: xml_to_item(el)}
return xml_to_dict(root)
x = simplexml_load_file('routines/test.xml')
print x
for y in x['root']:
print y
Run Code Online (Sandbox Code Playgroud)
输出:
{'root': {
'a': ['1'],
'aa': [{'b': [{'c': ['2']}, '2']}],
'aaaa': [{'bb': ['4']}],
'aaa': ['3'],
'aaaaa': ['5']
}}
a
aa
aaaa
aaa
aaaaa …Run Code Online (Sandbox Code Playgroud)