首页 > 解决方案 > 使用有序字典

问题描述

我正在学习 python 集合。关于 Ordered Dictionary 的描述是“ OrderedDict 保留插入键的顺序。常规 dict 不跟踪插入顺序,并且迭代它以任意顺序给出值。相比之下,插入项目的顺序被 OrderedDict 记住。

所以我试图通过一个程序来理解它:

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) 

输出

a 1
b 2
c 3
d 4

This is an Ordered Dict:

a 1
b 2
c 3
d 4
>>> 

但是两者的输出是相同的。那么我为什么要使用有序字典呢?

标签: pythondictionaryhash

解决方案


由于 python 3.7 字典顺序保证是插入顺序。检查此答案以获取类似的问题链接


推荐阅读