Python选择OrderedDi中的第i个元素

2024-05-16 20:11:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段按字母顺序排列词典的代码。 有没有办法在有序字典中选择第i个键并返回其相应的值?i、 e

import collections
initial = dict(a=1, b=2, c=2, d=1, e=3)
ordered_dict = collections.OrderedDict(sorted(initial.items(), key=lambda t: t[0]))
print(ordered_dict)

OrderedDict([('a', 1), ('b', 2), ('c', 2), ('d', 1), ('e', 3)])

我想在……的血管上起一些作用。。。

select = int(input("Input dictionary index"))
#User inputs 2
#Program looks up the 2nd entry in ordered_dict (c in this case)
#And then returns the value of c (2 in this case)

如何才能做到这一点? 谢谢。

(类似于Accessing Items In a ordereddict,但我只想输出键值对的值。)


Tags: the代码in字典字母thiscollectionsdict
3条回答

在Python 2中:

如果要访问密钥:

>>> ordered_dict.keys()[2]
'c'

如果要访问该值:

>>> ordered_dict.values()[2]
2

如果您使用的是Python 3,那么可以通过将keys方法返回的KeysView对象包装为一个列表来进行转换:

>>> list(ordered_dict.keys())[2]
'c'
>>> list(ordered_dict.values())[2]
2

不是最漂亮的解决方案,但它起作用了。

您需要使用OrderedDict还是只需要支持索引的dict类型?如果是后者,则考虑排序的dict对象。SortedDict(基于密钥排序顺序排序对)的一些实现支持快速n次索引。例如,sortedcontainers项目有一个带有随机访问索引的SortedDict类型。

在你的情况下,它看起来像:

>>> from sortedcontainers import SortedDict
>>> sorted_dict = SortedDict(a=1, b=2, c=2, d=1, e=3)
>>> print sorted_dict.iloc[2]
'c'

如果您做了大量查找,这将比重复迭代到所需索引快得多。

在这里使用^{}是有效的,因为为了订阅,我们不必创建任何中间列表。

from itertools import islice
print(next(islice(ordered_dict.items(), 2, None)))

如果你只想要价值,你可以

print ordered_dict[next(islice(ordered_dict, 2, None))]

相关问题 更多 >