dict和OrderedDict的异同(since 3.6)

2020年12月14日 / 50次阅读 / Last Modified 2021年4月2日
Dict

从python 3.6 开始,builtin的dict对象,也能够记录insert order,但还是跟collections.OrderedDict有不一样的细节。

看别人的文章说,python3.6开始,dict对象不仅仅是记录了插入键值对的顺序,整体性能也大幅提升。

对象比较时

两个dict对象比较,无论按什么顺序insert数据,只要数据是一样的,他们就是相等的:

>>> d1 = {}
>>> d1['a']=1
>>> d1['b']=2
>>> d1['c']=3
>>>
>>> d2 = {}
>>> d2['c']=3
>>> d2['a']=1
>>> d2['b']=2
>>>
>>> d1 == d2
True

而两个OrderedDict对象,要让它们相等,不仅数据要完全一样,插入顺序也要完全一样:

>>> from collections import OrderedDict
>>> od1 = OrderedDict()
>>> od1['a']=1
>>> od1['b']=2
>>> od1['c']=3
>>>
>>> od2 = OrderedDict()
>>> od2['c']=3
>>> od2['a']=1
>>> od2['b']=2
>>>
>>> od1 == od2
False

dict对象比较不看insert order;OrderedDict对象比较要看insert order;最后,dict对象和OrderedDict对象比较,也是不看order的:

>>> from collections import OrderedDict
>>>
>>> od = OrderedDict({'a':1,'b':2,'c':3})
>>> od
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
>>>
>>> nod = {'b':2,'a':1,'c':3}
>>> nod
{'b': 2, 'a': 1, 'c': 3}
>>>
>>> od == nod
True

Reordering

OrderedDict对象有一个move_to_end函数,是dict对象所没有的,我们可以用move_to_end函数来实现一定程度的reordering(重排序)。

>>> for k,v in od1.items():
...     print(k,v)
...
a 1
b 2
c 3
>>> od1.move_to_end('b')
>>> for k,v in od1.items():
...     print(k,v)
...
a 1
c 3
b 2
>>> od1.move_to_end('c', last=False)
>>> for k,v in od1.items():
...     print(k,v)
...
c 3
a 1
b 2

last参数默认是True,当为False时,就是反过来的顺序。

dict对象如果要实现move to end,可以先pop,然后重新insert到最后。

popitem

OrderedDict和dict虽然都有popitem成员函数,但是前者可以带一个参数,既可以LIFO,也可以FIFO。

-- EOF --

本文链接:https://www.pynote.net/archives/3037

留言区

《dict和OrderedDict的异同(since 3.6)》有5条留言

您的电子邮箱地址不会被公开。 必填项已用*标注

  • 麦新杰

    Changed in version 3.7: Dictionaries did not preserve insertion order in versions of Python before 3.6. In CPython 3.6, insertion order was preserved, but it was considered an implementation detail at that time rather than a language guarantee. [回复]

  • 麦新杰

    Dictionaries preserve insertion order, meaning that keys will be produced in the same order they were added sequentially over the dictionary. Replacing an existing key does not change the order, however removing a key and re-inserting it will add it to the end instead of keeping its old place. [回复]

  • 麦新杰

    dict对象在速度和内存方面,都要比OrderedDict要好! [回复]

  • 麦新杰

    OrderedDict was added to the standard library in Python 3.1. Its API is essentially the same as dict. However, OrderedDict iterates over keys and values in the same order that the keys were inserted. If a new entry overwrites an existing entry, then the order of items is left unchanged. If an entry is deleted and reinserted, then it will be moved to the end of the dictionary. [回复]

  • 麦新杰

    虽然从python3.6开始,dict有顺序了,但是当我们要访问dict对线中的第N个元素的时候,还是只能通过遍历的方式(O(N))。dict不支持随机存取(O(1))。 [回复]


前一篇:
后一篇:

More


©Copyright 麦新杰 Since 2019 Python笔记

go to top