在“重嵌套”结构中排序Python OrderedDict

2024-06-16 10:34:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的Python字典,我正在尝试将其排序为OrderedDict。在

fruits = {
    "apple": {
        "details": {
            "color": "green", 
            "dim": 100
        },
        "types": {
            "Akane": {
                "taste": "acceptable",
                "sort": 1
            },
            "McIntosh": {
                "taste": "delicious",
                "sort": 0
            }, 
            "Ambrosia": {
                "taste": "ok",
                "sort": 1
            }
        }
    },         
    "pear": {
    }, 
    "banana": {
    }, 
}

基本上,我想根据每个appleType的“sort”值对该子字典中的不同appleType进行排序。 最终,有序字典的理想状态应该如下所示:

^{pr2}$

我一直在研究sorted函数,但我不能很好地理解它,我不知道如何在嵌套结构中实现排序。在

fruits_sorted = OrderedDict(sorted(fruits.items(), key=lambda x: x[1]))

非常感谢任何帮助!在


Tags: apple字典排序greendetailssortcolortypes
1条回答
网友
1楼 · 发布于 2024-06-16 10:34:56

您的解决方案非常接近;您需要:

from collections import OrderedDict

apple_types = fruits['apple']['types']
types_sorted = OrderedDict(sorted(apple_types.items(), key=lambda x: -x[1]['sort']))

现在,types_sorted按您想要的排序顺序排列了苹果类型。如果你愿意的话,你可以把它放回原版词典里。在

这能回答你的问题吗?在

相关问题 更多 >