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

标签 python python-2.7 dictionary

<分区>

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

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()

但结果是一样的。

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

最佳答案

来源不应是字典。使用其他保证顺序的序列(列表、元组、..):

>>> from collections import OrderedDict as odict
>>> d = [('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)]
>>> print odict(d).keys()
['banana', 'apple', 'pear', 'orange']

关于python - 按索引获取字典中的有序键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26383142/

相关文章:

Google Calendar API v3 的 Python 客户端库插入事件抛出 "Missing end time"错误

python - 我从哪里可以获得 Mac OS X Lion 的 “Python Launcher”?

algorithm - 提高性能(超时错误)

java - 在字典程序中比较对象与ArrayList

c++ - 具有多个参数的 Map.emplace C++ 17

python - GIMP python 画线速度很慢

python - 我在 python 中使用startswith匹配一行后找到下一行,但行之间有多个空格

javascript - 无法在 Selenium Webdriver 中使用 send_keys 上传文件

python - wxPython 和高速公路 websockets

Javascript 语法字典(标准函数、对象、方法和关键字)