一 订购的信息 是一个dictionary子类,它可以记住第一次插入键的顺序。两者之间唯一的区别 dict() OrderedDict()是:
null
订购的信息 维持秩序 其中插入了键。常规dict不跟踪插入顺序,迭代它会以任意顺序给出值。相比之下,OrderedICT会记住插入项目的顺序。
Python3
# A Python program to demonstrate working of OrderedDict from collections import OrderedDict print ( "This is a Dict:" ) d = {} d[ 'a' ] = 1 d[ 'b' ] = 2 d[ 'c' ] = 3 d[ 'd' ] = 4 for key, value in d.items(): print (key, value) print ( "This is an Ordered Dict:" ) 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 1c 3b 2d 4This is an Ordered Dict:a 1b 2c 3d 4
要点:
1.关键值更改: 如果某个键的值发生更改,则该键在OrderedDict中的位置将保持不变。
Python3
# A Python program to demonstrate working of key # value change in OrderedDict from collections import OrderedDict print ( "Before:" ) od = OrderedDict() od[ 'a' ] = 1 od[ 'b' ] = 2 od[ 'c' ] = 3 od[ 'd' ] = 4 for key, value in od.items(): print (key, value) print ( "After:" ) od[ 'c' ] = 5 for key, value in od.items(): print (key, value) |
输出:
Before:a 1b 2c 3d 4After:a 1b 2c 5d 4
2.删除和重新插入 :删除并重新插入同一个键会将其按顺序向后推。但是,ICT会保持插入顺序。
Python3
# A Python program to demonstrate working of deletion # re-insertion in OrderedDict from collections import OrderedDict print ( "Before deleting:" ) od = OrderedDict() od[ 'a' ] = 1 od[ 'b' ] = 2 od[ 'c' ] = 3 od[ 'd' ] = 4 for key, value in od.items(): print (key, value) print ( "After deleting:" ) od.pop( 'c' ) for key, value in od.items(): print (key, value) print ( "After re-inserting:" ) od[ 'c' ] = 3 for key, value in od.items(): print (key, value) |
输出:
Before deleting:a 1b 2c 3d 4After deleting:a 1b 2d 4After re-inserting:a 1b 2d 4c 3
其他考虑 :
- Python版本2.7中的有序dict比普通dict消耗更多内存。这是由于底层的双链表实现保持了顺序。在Python 2.7中,Ordered Dict不是Dict子类,它是collections模块中的一个专用容器。
- 从Python 3.7开始,Python字典的插入顺序是有保证的。
- 有序Dict可以在 popitem 作用尝试用有序Dict实现LRU缓存。
本文由 斯里·桑凯斯·乌帕拉帕蒂 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END