简体   繁体   English

如何按照插入顺序从字典中检索项目?

[英]How do you retrieve items from a dictionary in the order that they're inserted?

是否可以按照插入的顺序从 Python 字典中检索项目?

The standard Python dict does this by default if you're using CPython 3.6+ (or Python 3.7+ for any other implementation of Python).如果您使用 CPython 3.6+(或 Python 3.7+ 用于任何其他 Python 实现),则标准 Python dict默认执行此操作。

On older versions of Python you can use collections.OrderedDict .在旧版本的 Python 上,您可以使用collections.OrderedDict

Use OrderedDict(), available since version 2.7使用 OrderedDict(),自 2.7 版起可用

Just a matter of curiosity:只是一个好奇的问题:

from collections import OrderedDict
a = {}
b = OrderedDict()
c = OrderedDict()

a['key1'] = 'value1'
a['key2'] = 'value2'

b['key1'] = 'value1'
b['key2'] = 'value2'

c['key2'] = 'value2'
c['key1'] = 'value1'

print a == b  # True
print a == c  # True
print b == c  # False

As of Python 3.7, the standard dict preserves insertion order.从 Python 3.7 开始,标准 dict 保留插入顺序。 From the docs :文档

Changed in version 3.7: Dictionary order is guaranteed to be insertion order.在 3.7 版更改: 字典顺序保证是插入顺序。 This behavior was implementation detail of CPython from 3.6.此行为是 3.6 中 CPython 的实现细节。

So, you should be able to iterate over the dictionary normally or use popitem() .因此,您应该能够正常遍历字典或使用popitem()

The other answers are correct;其他答案是正确的; it's not possible, but you could write this yourself.这是不可能的,但你可以自己写这个。 However, in case you're unsure how to actually implement something like this, here's a complete and working implementation that subclasses dict which I've just written and tested.但是,如果您不确定如何实际实现这样的东西,这里有一个完整且有效的实现,它是我刚刚编写和测试的 dict 的子类。 (Note that the order of values passed to the constructor is undefined but will come before values passed later, and you could always just not allow ordered dicts to be initialized with values.) (请注意,传递给构造函数的值的顺序是未定义的,但会在稍后传递的值之前出现,并且您总是可以不允许使用值初始化有序的字典。)

class ordered_dict(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)
        self._order = self.keys()

    def __setitem__(self, key, value):
        dict.__setitem__(self, key, value)
        if key in self._order:
            self._order.remove(key)
        self._order.append(key)

    def __delitem__(self, key):
        dict.__delitem__(self, key)
        self._order.remove(key)

    def order(self):
        return self._order[:]

    def ordered_items(self):
        return [(key,self[key]) for key in self._order]


od = ordered_dict()
od["hello"] = "world"
od["goodbye"] = "cruel world"
print od.order()            # prints ['hello', 'goodbye']

del od["hello"]
od["monty"] = "python"
print od.order()            # prints ['goodbye', 'monty']

od["hello"] = "kitty"
print od.order()            # prints ['goodbye', 'monty', 'hello']

print od.ordered_items()
# prints [('goodbye','cruel world'), ('monty','python'), ('hello','kitty')]

You can't do this with the base dict class -- it's ordered by hash.你不能用基本的 dict 类来做到这一点——它是按哈希排序的。 You could build your own dictionary that is really a list of key,value pairs or somesuch, which would be ordered.您可以构建自己的字典,它实际上是一个键、值对或类似的列表,它们将被排序。

Or, just make the key a tuple with time.now() as the first field in the tuple.或者,只需将键作为元组中的第一个字段 time.now() 即可。

Then you can retrieve the keys with dictname.keys(), sort, and voila!然后您可以使用 dictname.keys() 检索键,排序,瞧!

Gerry格里

I've used StableDict before with good success.我之前使用过 StableDict 并取得了成功。

http://pypi.python.org/pypi/StableDict/0.2 http://pypi.python.org/pypi/StableDict/0.2

Or use any of the implementations for the PEP-372 described here , like the odict module from the pythonutils .或使用任何针对该实现的PEP-372描述这里,像odict模块pythonutils

I successfully used the pocoo.org implementation, it is as easy as replacing your我成功使用了 pocoo.org 实现,就像替换你的一样简单

my_dict={}
my_dict["foo"]="bar"

with

my_dict=odict.odict()
my_dict["foo"]="bar"

and require just this file并且只需要这个文件

除非您将密钥存储在单独的列表中以供以后参考,否则这是不可能的。

What you can do is insert the values with a key representing the order inputted, and then call sorted() on the items.您可以做的是使用代表输入顺序的键插入值,然后对项目调用sorted()

>>> obj = {}
>>> obj[1] = 'Bob'
>>> obj[2] = 'Sally'
>>> obj[3] = 'Joe'
>>> for k, v in sorted(obj.items()):
...     print v
... 
Bob
Sally
Joe
>>> 

如果您不需要 dict 功能,而只需要按照插入的顺序返回元组,那么队列不是更好用吗?

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

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