gpt4 book ai didi

python - 如何对 OrderedDict 的 OrderedDict 进行排序?

转载 作者:IT老高 更新时间:2023-10-28 20:34:50 31 4
gpt4 key购买 nike

我正在尝试通过 '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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com