通过索引访问collections.OrderedDict中的项目 [英] Accessing items in an collections.OrderedDict by index

查看:52
本文介绍了通过索引访问collections.OrderedDict中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有以下代码:

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

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

Is there a way I can access the items in a numbered manner, like:

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

推荐答案

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

If its an OrderedDict() you can easily access the elements by indexing by getting the tuples of (key,value) pairs as follows

>>> 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将返回可迭代的dict视图对象,而不是列表.我们需要将调用包装到列表上,以便可以建立索引

dict.items would return an iterable dict view object rather than a list. We need to wrap the call onto a list in order to make the indexing possible

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

这篇关于通过索引访问collections.OrderedDict中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆