在 "heavily nested" 结构中对 Python OrderedDict 进行排序

Sorting Python OrderedDict in "heavily nested" structure

我有以下 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 进行排序。 最后,理想情况下,有序字典应如下所示:

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

我一直在研究 sorted 函数,但我不太明白,我不确定如何在嵌套结构中实现排序。

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

非常感谢任何帮助!

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

from collections import OrderedDict

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

现在,types_sorted 已经按照您想要的顺序排列了苹果类型。如果你愿意,你可以把它放回原来的字典。

这是否回答了您的问题?