通过索引访问 collections.OrderedDict 中的项目

新手上路,请多包涵

可以说我有以下代码:

 import collections
d = collections.OrderedDict()
d['foo'] = 'python'
d['bar'] = 'spam'

有没有一种方法可以以编号方式访问项目,例如:

 d(0) #foo's Output
d(1) #bar's Output

原文由 Billjk 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 485
2 个回答

如果它是 OrderedDict() 您可以通过获取(键,值)对的元组进行索引来轻松访问元素,如下所示

>>> import collections
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'
>>> d.items()
[('foo', 'python'), ('bar', 'spam')]
>>> d.items()[0]
('foo', 'python')
>>> d.items()[1]
('bar', 'spam')

Python 3.X 的注意事项

dict.items 将返回一个 可迭代的字典视图对象 而不是一个列表。我们需要将调用包装到一个列表中,以便使索引成为可能

>>> items = list(d.items())
>>> items
[('foo', 'python'), ('bar', 'spam')]
>>> items[0]
('foo', 'python')
>>> items[1]
('bar', 'spam')

原文由 Abhijit 发布,翻译遵循 CC BY-SA 3.0 许可协议

您是否必须使用 OrderedDict,或者您是否特别想要一种以某种方式排序并具有快速位置索引的类似地图的类型?如果是后者,则考虑 Python 的许多排序字典类型之一(它根据键排序顺序对键值对进行排序)。一些实现还支持快速索引。例如, sortedcontainers 项目有一个 SortedDict 类型就是为了这个目的。

 >>> from sortedcontainers import SortedDict
>>> sd = SortedDict()
>>> sd['foo'] = 'python'
>>> sd['bar'] = 'spam'
>>> print sd.iloc[0] # Note that 'bar' comes before 'foo' in sort order.
'bar'
>>> # If you want the value, then simple do a key lookup:
>>> print sd[sd.iloc[1]]
'python'

原文由 GrantJ 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题