作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在尝试通过 'depth' 键对 OrderedDict 中的 OrderedDict 进行排序。有什么解决方案可以对该 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)
])),
])
排序后的字典应该是这样的:
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()
。
关于python - 如何对 OrderedDict 的 OrderedDict 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8031418/
我是一名优秀的程序员,十分优秀!