AnOrderedDict是一个字典子类, 可记住第一次插入键的顺序。之间的唯一区别dict()和OrderedDict()是:
OrderedDict保留订单在其中插入密钥。常规dict不会跟踪插入顺序, 并且对其进行迭代会以任意顺序给出值。相比之下, OrderedDict会记住项的插入顺序。
# A Python program to demonstrate working of OrderedDict
from collections import OrderedDict
print ( "This is a Dict:\n" )
d = {}
d[ 'a' ] = 1
d[ 'b' ] = 2
d[ 'c' ] = 3
d[ 'd' ] = 4
for key, value in d.items():
print (key, value)
print ( "\nThis is an Ordered Dict:\n" )
od = OrderedDict()
od[ 'a' ] = 1
od[ 'b' ] = 2
od[ 'c' ] = 3
od[ 'd' ] = 4
for key, value in od.items():
print (key, value)
输出如下:
This is a Dict:
('a', 1)
('c', 3)
('b', 2)
('d', 4)
This is an Ordered Dict:
('a', 1)
('b', 2)
('c', 3)
('d', 4)
重要事项:
键值更改:
如果某个键的值被更改, 则该键的位置在OrderedDict中保持不变。
# A Python program to demonstrate working of key
# value change in OrderedDict
from collections import OrderedDict
print ( "Before:\n" )
od = OrderedDict()
od[ 'a' ] = 1
od[ 'b' ] = 2
od[ 'c' ] = 3
od[ 'd' ] = 4
for key, value in od.items():
print (key, value)
print ( "\nAfter:\n" )
od[ 'c' ] = 5
for key, value in od.items():
print (key, value)
输出如下:
Before:
('a', 1)
('b', 2)
('c', 3)
('d', 4)
After:
('a', 1)
('b', 2)
('c', 5)
('d', 4)
删除并重新插入
:删除并重新插入相同的密钥会将其推回后面, 因为OrderedDict会保持插入顺序。
# A Python program to demonstrate working of deletion
# re-inserion in OrderedDict
from collections import OrderedDict
print ( "Before deleting:\n" )
od = OrderedDict()
od[ 'a' ] = 1
od[ 'b' ] = 2
od[ 'c' ] = 3
od[ 'd' ] = 4
for key, value in od.items():
print (key, value)
print ( "\nAfter deleting:\n" )
od.pop( 'c' )
for key, value in od.items():
print (key, value)
print ( "\nAfter re-inserting:\n" )
od[ 'c' ] = 3
for key, value in od.items():
print (key, value)
输出如下:
Before deleting:
('a', 1)
('b', 2)
('c', 3)
('d', 4)
After deleting:
('a', 1)
('b', 2)
('d', 4)
After re-inserting:
('a', 1)
('b', 2)
('d', 4)
('c', 3)
其他注意事项:
- Python 2.7版中的有序字典比普通字典消耗更多的内存。这是由于用于保持顺序的底层双链表实现。在Python 2.7中, Ordered Dict不是dict的子类, 它是来自collections模块的专用容器。
- 从Python 3.7开始, 可以保证Python字典的插入顺序。
- 借助以下命令, 可以将有序词典用作堆栈弹出项目功能。尝试使用有序字典实现LRU缓存。
如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。
注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。