【发布时间】:2015-04-17 13:10:21
【问题描述】:
我有以下 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 的“排序”值对该子词典中的不同 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]))
非常感谢任何帮助!
【问题讨论】:
标签: python sorting nested ordereddictionary