如何对 OrderedDict 的 OrderedDict 进行排序? [英] How to sort OrderedDict of OrderedDict?
问题描述
我正在尝试按 'depth' 键对 OrderedDict 中的 OrderedDict 进行排序.有什么解决方案可以对 Dictionary 进行排序吗?
I'm trying to sort OrderedDict in OrderedDict by 'depth' key. Is there any solution to sort that Dictionary ?
OrderedDict([
(2, OrderedDict([
('depth', 0),
('height', 51),
('width', 51),
('id', 100)
])),
(1, OrderedDict([
('depth', 2),
('height', 51),
('width', 51),
('id', 55)
])),
(0, OrderedDict([
('depth', 1),
('height', 51),
('width', 51),
('id', 48)
])),
])
排序后的字典应该是这样的:
Sorted dict should look like this:
OrderedDict([
(2, OrderedDict([
('depth', 0),
('height', 51),
('width', 51),
('id', 100)
])),
(0, OrderedDict([
('depth', 1),
('height', 51),
('width', 51),
('id', 48)
])),
(1, OrderedDict([
('depth', 2),
('height', 51),
('width', 51),
('id', 55)
])),
])
知道如何获得它吗?
推荐答案
您必须创建一个新方案,因为 OrderedDict
是按插入顺序排序的.
You'll have to create a new one since OrderedDict
is sorted by insertion order.
在您的情况下,代码如下所示:
In your case the code would look like this:
foo = OrderedDict(sorted(foo.iteritems(), key=lambda x: x[1]['depth']))
参见 http://docs.python.org/dev/library/collections.html#ordereddict-examples-and-recipes 了解更多示例.
See http://docs.python.org/dev/library/collections.html#ordereddict-examples-and-recipes for more examples.
注意,对于 Python 3,您需要使用 .items()
而不是 .iteritems()
.
Note for Python 3 you will need to use .items()
instead of .iteritems()
.
这篇关于如何对 OrderedDict 的 OrderedDict 进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!