Skip to main content
 首页 » 编程设计

python之按索引获取字典中的有序键

2025年05月04日1698°冷暖

<分区>

这看起来应该是一件相当简单的事情,但我一直做不到。假设我有一本像这样的字典:

d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2} 

我想访问键按照它们在字典中的存储顺序。我原以为这会起作用:

print d.keys()[0] 
banana 

但实际结果是:

orange 

显然这是因为 dictionaries are unordered在 python 。我试过使用 collections.OrderedDict :

from collections import OrderedDict as odict 
d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2} 
print odict(d).keys() 

但结果是一样的。

我该怎么做?鉴于执行此任务的明显复杂性,我是否应该不这样做?我还能如何按顺序访问字典中的键?