首页 > 解决方案 > 用字符串数字键对字典进行数字排序的最 Pythonic 方法是什么?

问题描述

这是我的格式,dict

{
    "server" : {
        "2" : {
            name : "Chris",
            text : "Hello!"
        },
        "1" : {
            name : "David",
            text : "Hey!"
        }
    }
}

dict['server']尽管键是字符串,但如何按数字排序?我能想出的所有方法都需要多个名称,而且一点也不像 Pythonic。

标签: pythonpython-2.7sortingdictionary

解决方案


使用collections.OrderedDict

前任:

import collections
d = {
    "server" : {
        "2" : {
            "name" : "Chris",
            "text" : "Hello!"
        },
        "1" : {
            "name" : "David",
            "text" : "Hey!"
        }
    }
}

print collections.OrderedDict(sorted(d["server"].items(), key=lambda x: int(x[0])))

输出:

OrderedDict([('1', {'text': 'Hey!', 'name': 'David'}), ('2', {'text': 'Hello!', 'name': 'Chris'})])

推荐阅读