访问项目在ordereddict中 [英] Accessing Items In a ordereddict
本文介绍了访问项目在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
推荐答案
< code> OrderedDict()您可以通过索引来容易地访问元素,通过获得(key,value)对的元组如下
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.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')
这篇关于访问项目在ordereddict中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文