问题描述
我正在尝试通过'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)
])),
])
任何想法如何得到它?
Any idea how to get it?
推荐答案
由于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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!