首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何访问ordereddict中的项?

如何访问ordereddict中的项?
EN

Stack Overflow用户
提问于 2018-05-03 08:26:19
回答 2查看 0关注 0票数 0

假设我有以下代码:

代码语言:txt
复制
import collections
d = collections.OrderedDict()
d['foo'] = 'python'
d['bar'] = 'spam'

是否有办法以编号的方式访问这些项目,例如:

代码语言:txt
复制
d(0) #foo's Output
d(1) #bar's Output
EN

回答 2

Stack Overflow用户

发布于 2018-05-03 16:36:36

代码语言:txt
复制
>>> 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')
代码语言:txt
复制
>>> items = list(d.items())
>>> items
[('foo', 'python'), ('bar', 'spam')]
>>> items[0]
('foo', 'python')
>>> items[1]
('bar', 'spam')
票数 0
EN

Stack Overflow用户

发布于 2018-05-03 17:27:37

代码语言:txt
复制
>>> 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'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100004020

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档