[英]How to sort OrderedDict of OrderedDict - Python
我试图通过'depth'键在OrderedDict中对OrderedDict进行排序。 是否有任何解决方案来排序该词典?
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)
])),
])
排序的dict应如下所示:
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
按插入顺序排序。
在您的情况下,代码将如下所示:
foo = OrderedDict(sorted(foo.iteritems(), key=lambda x: x[1]['depth']))
有关更多示例,请参阅http://docs.python.org/dev/library/collections.html#ordereddict-examples-and-recipes 。
注意Python 3,您需要使用.items()
而不是.iteritems()
。
>>> OrderedDict(sorted(od.items(), key=lambda item: item[1]['depth']))
有时您可能希望保留初始字典而不是创建新字典。
在这种情况下,您可以执行以下操作:
temp = sorted(list(foo.items()), key=lambda x: x[1]['depth'])
foo.clear()
foo.update(temp)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.