我正在尝试根据OrderedDict‘depth’键在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)
])),
]) 排序后的数据应该如下所示:
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)
])),
]) 知道怎么弄到吗?
发布于 2011-11-07 00:09:16
您必须创建一个新的,因为OrderedDict是按插入顺序排序的。
在您的示例中,代码如下所示:
foo = OrderedDict(sorted(foo.items(), key=lambda x: x[1]['depth']))有关更多示例,请参见http://docs.python.org/dev/library/collections.html#ordereddict-examples-and-recipes。
注意,对于Python2,您需要使用.iteritems()而不是.items()。
发布于 2011-11-07 00:12:23
>>> OrderedDict(sorted(od.items(), key=lambda item: item[1]['depth']))发布于 2018-04-05 05:47:19
有时,您可能希望保留初始字典,而不创建新字典。
在这种情况下,您可以执行以下操作:
temp = sorted(list(foo.items()), key=lambda x: x[1]['depth'])
foo.clear()
foo.update(temp)https://stackoverflow.com/questions/8031418
复制相似问题