Skip to main content
 首页 » 编程设计

python之字典应该按公司顺序存储 key 吗

2025年05月04日13lovecherry

我有一个以整数作为键的字典。请告诉我,字典是否存储带有排序键的数据?

我写了一小段代码来测试(如下):

>>>  
>>> d = {1: 'a', 3: 'a'} 
>>> d 
{1: 'a', 3: 'a'} 
>>> d[2] = 'a' 
>>> d 
{1: 'a', 2: 'a', 3: 'a'} 
>>>  

但我不确定这种行为是否标准并且一直有效。

请您参考如下方法:

python 中的字典没有排序。在这里阅读更多关于字典的信息: http://docs.python.org/library/stdtypes.html?highlight=dict#dict

但是你可以使用sorted python built-in method对键进行排序:

for k in sorted(myDict): 
    myDict[k] # do something 

或在此处查找 collections.OrderedDict implementation

您也可以混合使用 sorted 方法和 OrderedDict 以便稍后使用(确保这只会在您不向其中添加新项目的情况下出现 - 否则最好使用 sorted 方法):

d = {1: 'a', 3: 'a'}    
from collections import OrderedDict    
sorted_d = OrderedDict((k, d[k]) for k in sorted(d))