简体   繁体   English

使用有序字典

[英]Use of Ordered Dict

I am learning about python collections.我正在学习 python collections。 It is written about Ordered Dictionary that " OrderedDict preserves the order in which the keys are inserted. A regular dict doesn't track the insertion order, and iterating it gives the values in an arbitrary order. By contrast, the order the items are inserted is remembered by OrderedDict. "关于 Ordered Dictionary 的描述是“ OrderedDict 保留插入键的顺序。常规 dict 不跟踪插入顺序,并且迭代它以任意顺序给出值。相比之下,插入项目的顺序被 OrderedDict 记住。

So i tried to understand it by a program:所以我试图通过一个程序来理解它:

from collections import OrderedDict 

d = dict()
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) 

OUTPUT OUTPUT

a 1
b 2
c 3
d 4

This is an Ordered Dict:

a 1
b 2
c 3
d 4
>>> 

But the output for both is the same.但是两者的 output 是相同的。 So why should I use Ordered Dictionary?那么我为什么要使用有序字典呢?

Since python 3.7 Dictionary order is guaranteed to be insertion order.由于 python 3.7 字典顺序保证为插入顺序。 check this answer for similar question link检查此答案以获取类似的问题链接

because-- If the value of a certain key is changed, the position of the key remains unchanged in OrderedDict.因为——如果某个key的值发生了变化,那么这个key的position在OrderedDict中保持不变

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

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