Skip to main content
 首页 » 编程设计

python之对字典的字典进行排序

2025年05月04日12lyhabc

我有一个字典的字典,看起来像这样:

"abc": { 
    "name": "Joey", 
    "order": 3 
    }, 
"def": { 
    "name": "Allen", 
    "order": 2 
    }, 
"ghi": { 
    "name": "Tim", 
    "order": 1 
    } 

现在,我想根据“顺序”值对这本字典进行排序。

意思是,排序后的字典看起来像:

"ghi": { 
    "name": "Tim", 
    "order": 1 
    } 
"def": { 
    "name": "Allen", 
    "order": 2 
    }, 
"abc": { 
    "name": "Joey", 
    "order": 3 
    } 

我该怎么做? 我找到了对字典列表进行排序的方法,但不是字典的字典。

请您参考如下方法:

使用sorted按“顺序”和 collections.OrderedDict 排序存储结果,

import collections 
 
d = { 
    "abc": { 
        "name": "Joey", 
        "order": 3 
        }, 
    "def": { 
        "name": "Allen", 
        "order": 2 
        }, 
    "ghi": { 
        "name": "Tim", 
        "order": 1 
        } 
    } 
 
result = collections.OrderedDict(sorted(d.items(), key=lambda t:t[1]["order"])) 
 
# Output 
print(result) 
OrderedDict([('ghi', {'name': 'Tim', 'order': 1}),  
            ('def', {'name': 'Allen', 'order': 2}),  
            ('abc', {'name': 'Joey', 'order': 3})])