Python OrderedDict 不保持元素顺序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15733558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:49:28  来源:igfitidea点击:

Python OrderedDict not keeping element order

pythonpython-2.7ordereddictionary

提问by Ecolitan

I'm trying to create an OrderedDict object but no sooner do I create it, than the elements are all jumbled.

我正在尝试创建一个 OrderedDict 对象,但我刚创建它,元素就变得混乱了。

This is what I do:

这就是我所做的:

from collections import OrderedDict
od = OrderedDict({(0,0):[2],(0,1):[1,9],(0,2):[1,5,9]})

The elements don't stay in the order I assign

元素不按照我分配的顺序

od
OrderedDict([((0, 1), [1, 9]), ((0, 0), [2]), ((0, 2), [1, 5, 9])])

docs.python.org doesn't have an example and I can't figure out why the order is getting jumbled. Any help is greatly appreciated.

docs.python.org 没有示例,我无法弄清楚为什么订单变得混乱。任何帮助是极大的赞赏。

采纳答案by Gareth Latty

Your problem is that you are constructing a dictto give the initial data to the OrderedDict- this dictdoesn'tstore any order, so the order is lost before it gets to the OrderedDict.

您的问题是您正在构建 adict以将初始数据提供给OrderedDict- 这dict存储任何订单,因此订单在到达OrderedDict.

The solution is to build from an ordered data type - the easiest being a listof tuples:

解决方案是从有序数据类型构建 - 最简单的是 a listof tuples:

>>> from collections import OrderedDict
>>> od = OrderedDict([((0, 0), [2]), ((0, 1), [1, 9]), ((0, 2), [1, 5, 9])])
>>> od
OrderedDict([((0, 0), [2]), ((0, 1), [1, 9]), ((0, 2), [1, 5, 9])])

It's worth noting that this is why OrderedDictuses the syntax it does for it's string representation - string representations should try to be valid Python code to reproduce the object where possible, and that's why the output uses a list of tuples instead of a dict.

值得注意的是,这就是为什么OrderedDict使用它为字符串表示所做的语法 - 字符串表示应该尝试成为有效的 Python 代码以在可能的情况下重现对象,这就是为什么输出使用元组列表而不是 dict。

Edit: As of Python 3.6, kwargsis ordered, so you can use keyword arguments instead, provided you are on an up-to-date Python version.

编辑:从 Python 3.6 开始,kwargsisordered,因此您可以改用关键字参数,前提是您使用的是最新的 Python 版本。

As of 3.7, this is also true for dicts (it was for CPython in 3.6, but the language spec didn't specify it, so using OrderedDictwas still required for compatibility). This means if you can assume a 3.7+ environment, you can often drop OrderedDictaltogether, or construct one from a regular dictif you need a specific feature (e.g: order to matter for equality).

从 3.7 开始,对于dicts也是如此(在 3.6 中用于 CPython,但是语言规范没有指定它,因此OrderedDict仍然需要使用以实现兼容性)。这意味着如果您可以假设 3.7+ 环境,您通常可以OrderedDict完全放弃,或者dict如果您需要特定功能(例如:为了平等而重要),则可以从常规构建一个。