Python 将 dict 转换为 OrderedDict

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15711755/
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:45:02  来源:igfitidea点击:

Converting dict to OrderedDict

pythonordereddictionary

提问by pythonpiboy

I am having some trouble using the collections.OrderedDictclass. I am using Python 2.7 on Raspbian, the Debian distro for Raspberry Pi. I am trying to print two dictionaries in order for comparison (side-by-side) for a text-adventure. The order is essential to compare accurately. No matter what I try the dictionaries print in their usual unordered way.

我在使用collections.OrderedDict课程时遇到了一些问题。我在 Raspbian(Raspberry Pi 的 Debian 发行版)上使用 Python 2.7。我正在尝试打印两本词典,以便进行文本冒险的比较(并排)。顺序对于准确比较至关重要。无论我尝试什么,字典都以通常的无序方式打印。

Here's what I get when I do it on my RPi:

这是我在 RPi 上执行此操作时得到的结果:

import collections

ship = {"NAME": "Albatross",
         "HP":50,
         "BLASTERS":13,
         "THRUSTERS":18,
         "PRICE":250}

ship = collections.OrderedDict(ship)

print ship
# OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)])

Obviously there is something not right because it is printing the function call and putting the keys and value groups into a nested list...

显然有些不对劲,因为它正在打印函数调用并将键和值组放入嵌套列表中...

This is what I got by running something similar on my PC:

这是我通过在我的 PC 上运行类似的东西得到的:

import collections

Joe = {"Age": 28, "Race": "Latino", "Job": "Nurse"}
Bob = {"Age": 25, "Race": "White", "Job": "Mechanic", "Random": "stuff"}

#Just for clarity:
Joe = collections.OrderedDict(Joe)
Bob = collections.OrderedDict(Bob)

print Joe
# OrderedDict([('Age', 28), ('Race', 'Latino'), ('Job', 'Nurse')])
print Bob
# OrderedDict([('Age', 25), ('Race', 'White'), ('Job', 'Mechanic'), ('Random', 'stuff')])

This time, it is in order, but it shouldn't be printing the other things though right? (The putting it into list and showing function call.)

这一次,它是有序的,但它应该不会打印其他东西吧?(将其放入列表并显示函数调用。)

Where am I making my error? It shouldn't be anything to do with the pi version of Python because it is just the Linux version.

我在哪里犯了错误?它应该与 Python 的 pi 版本没有任何关系,因为它只是 Linux 版本。

采纳答案by Martijn Pieters

You are creating a dictionary first, then passing that dictionary to an OrderedDict. For Python versions < 3.6 (*), by the time you do that, the ordering is no longer going to be correct. dictis inherently not ordered.

首先创建一个字典,然后将该字典传递给OrderedDict. 对于 Python 版本 < 3.6 (*),当您这样做时,排序将不再正确。dict本质上不是有序的。

Pass in a sequence of tuples instead:

而是传入一系列元组:

ship = [("NAME", "Albatross"),
        ("HP", 50),
        ("BLASTERS", 13),
        ("THRUSTERS", 18),
        ("PRICE", 250)]
ship = collections.OrderedDict(ship)

What you see when you print the OrderedDictis it's representation, and it is entirely correct. OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)])just shows you, in a reproducablerepresentation, what the contents are of the OrderedDict.

打印时您看到的OrderedDict是它的表示,它是完全正确的。OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)])只是以可重现的表示形式向您展示OrderedDict.



(*): In the CPython 3.6 implementation, the dicttype was updated to use a more memory efficient internal structure that has the happy side effect of preserving insertion order, and by extension the code shown in the question works without issues. As of Python 3.7, the Python language specificationhas been updated to require that all Python implementations must follow this behaviour. See this other answer of minefor details and also why you'd still may want to use an OrderedDict()for certain cases.

(*):在 CPython 3.6 实现中,该dict类型已更新为使用内存效率更高的内部结构,该结构具有保留插入顺序的快乐副作用,并且通过扩展,问题中显示的代码可以正常工作。从 Python 3.7 开始,Python 语言规范已更新为要求所有 Python 实现都必须遵循此行为。有关详细信息以及为什么您仍然可能希望在某些情况下使用 an ,请参阅我的另一个答案OrderedDict()

回答by Abdul Majeed

Most of the time we go for OrderedDict when we required a custom order not a generic one like ASC etc.

大多数时候,当我们需要自定义订单而不是 ASC 等通用订单时,我们会选择 OrderedDict。

Here is the proposed solution:

这是建议的解决方案:

import collections
ship = {"NAME": "Albatross",
         "HP":50,
         "BLASTERS":13,
         "THRUSTERS":18,
         "PRICE":250}

ship = collections.OrderedDict(ship)

print ship


new_dict = collections.OrderedDict()
new_dict["NAME"]=ship["NAME"]
new_dict["HP"]=ship["HP"]
new_dict["BLASTERS"]=ship["BLASTERS"]
new_dict["THRUSTERS"]=ship["THRUSTERS"]
new_dict["PRICE"]=ship["PRICE"]


print new_dict

This will be output:

这将输出:

OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)])
OrderedDict([('NAME', 'Albatross'), ('HP', 50), ('BLASTERS', 13), ('THRUSTERS', 18), ('PRICE', 250)])

Note: The new sorted dictionaries maintain their sort order when entries are deleted. But when new keys are added, the keys are appended to the end and the sort is not maintained.(official doc)

注意:删除条目时,新的排序字典会保持其排序顺序。但是当添加新键时,键被附加到末尾并且排序不维护。(官方文档

回答by Jan Rozycki

If you can't edit this part of code where your dict was defined you can still order it at any point in any way you want, like this:

如果您无法编辑定义 dict 的这部分代码,您仍然可以随时以任何您想要的方式对其进行排序,如下所示:

from collections import OrderedDict

order_of_keys = ["key1", "key2", "key3", "key4", "key5"]
list_of_tuples = [(key, your_dict[key]) for key in order_of_keys]
your_dict = OrderedDict(list_of_tuples)

回答by Mohammad-Ali

Use dict.items(); it can be as simple as following:

使用 dict.items(); 它可以简单如下:

ship = collections.OrderedDict(ship.items())