简体   繁体   English

python 3.7 中的无序字典

[英]Unordered dict in python 3.7

Dictionaries in python are ordered since Python 3.6 python 中的词典自 Python 3.6 起被排序

From - https://stackoverflow.com/a/39980744/4647107来自 - https://stackoverflow.com/a/39980744/4647107

Are dictionaries ordered in Python 3.6+?字典是在 Python 3.6+ 中订购的吗?

They are insertion ordered.它们是插入顺序的。 As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted.从 Python 3.6 开始,对于 Python 的 CPython 实现,字典会记住插入项目的顺序。 This is considered an implementation detail in Python 3.6;这被认为是 Python 3.6 中的一个实现细节; you need to use OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python.如果您希望在 Python 的其他实现中保证插入顺序,则需要使用 OrderedDict。

As of Python 3.7, this is no longer an implementation detail and instead becomes a language feature.从 Python 3.7 开始,这不再是实现细节,而是成为语言功能。 From a python-dev message by GvR:来自 GvR 的 python-dev 消息:

Make it so.做到这一点。 "Dict keeps insertion order" is the ruling. “字典保持插入顺序”是裁决。 Thanks!谢谢!

This simply means that you can depend on it.这仅仅意味着您可以信赖它。 Other implementations of Python must also offer an insertion ordered dictionary if they wish to be a conforming implementation of Python 3.7.如果 Python 的其他实现希望成为 Python 3.7 的一致实现,则它们也必须提供插入顺序字典。

Is there a way to implement an unordered dictionary in python now?现在有没有办法在python中实现无序字典?

You can fake it:你可以伪造它:

>>> import random
>>> d={'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]}
>>> items=list(d.items())
>>> random.shuffle(items)
>>> dict(items)
{'c': [7, 8, 9], 'b': [4, 5, 6], 'a': [1, 2, 3]}
>>> 

As a few people have mentioned it would help to understand why you would like an unordered dict.正如一些人所提到的,这将有助于理解为什么你想要一个无序的 dict。 Personally I was looking for an unordered dict because I was working with OrderedDicts, and their behavior meant that I couldn't directly compare them using == .就我个人而言,我正在寻找一个无序的 dict,因为我正在使用 OrderedDicts,而它们的行为意味着我无法使用==直接比较它们。 For example:例如:

In [1]: from collections import OrderedDict
In [2]: dict_1 = OrderedDict([('a', 0), ('b', 1), ('c', 2)])
In [3]: dict_2 = OrderedDict([('c', 2), ('b', 1), ('a', 0)])
In [4]: dict_1 == dict_2
Out[4]: False

A simple solution to this is to turn the OrderedDict back into a dict.对此的一个简单解决方案是将 OrderedDict 重新转换为 dict。

In [5]: dict(dict_1) == dict(dict_2)
Out[5]: True

Might be too late to answer but here's what I used,可能来不及回答,但这是我用过的,

class UnorderedDict:
    def __setitem__(self, key, value):
        setattr(self, key, value)
    def __getitem__(self, key):
        return getattr(self, key)
test = UnorderedDict()
test["key"] = "yay"
print(test["key"])

It sets and gets attribute, this doesn't have any order afaik.它设置并获取属性,这没有任何顺序 afaik。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM