📌  相关文章
📜  Python中的 OrderedDict

📅  最后修改于: 2022-05-13 01:54:37.614000             🧑  作者: Mango

Python中的 OrderedDict

OrderedDict是一个字典子类,它记住第一次插入键的顺序。 dict() 和 OrderedDict() 之间的唯一区别是:

OrderedDict保留插入键的顺序。常规 dict 不跟踪插入顺序并对其进行迭代以任意顺序给出值。相反,插入项目的顺序由 OrderedDict 记住。

Python3
# 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)


Python3
# 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)


Python3
# A Python program to demonstrate working of deletion
# re-insertion 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)


输出:

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

要点:

1.键值变化:如果某个键的值发生了变化,则该键在OrderedDict中的位置保持不变。

Python3

# 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

2. 删除和重新插入:删除和重新插入同一个键会像 OrderedDict 一样将其推到后面,但是会保持插入的顺序。

Python3

# A Python program to demonstrate working of deletion
# re-insertion 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 子类,它是来自集合模块的专用容器。
  • 从Python 3.7 开始,保证了Python字典的插入顺序。
  • popitem函数的帮助下,Ordered Dict 可以用作堆栈。尝试使用 Ordered Dict 实现 LRU 缓存。