相关疑难解决方法(0)

如何按值对字典进行排序?

我有一个从数据库中的两个字段读取的值字典:字符串字段和数字字段.字符串字段是唯一的,因此这是字典的键.

我可以对键进行排序,但是如何根据值进行排序?

注意:我已阅读Stack Overflow问题如何按Python中字典的值对字典列表进行排序?并且可能可以更改我的代码以获得字典列表,但由于我不需要字典列表,我想知道是否有更简单的解决方案.

python sorting dictionary

3424
推荐指数
31
解决办法
249万
查看次数

在python中排序字典键

我有一个dict,其中每个键引用一个int值.根据值将键排序到列表中的最佳方法是什么?

python sorting

128
推荐指数
3
解决办法
14万
查看次数

如何重写此函数以实现OrderedDict?

我有以下函数,它将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)

python xml collections lxml

13
推荐指数
1
解决办法
7186
查看次数

标签 统计

python ×3

sorting ×2

collections ×1

dictionary ×1

lxml ×1

xml ×1