我有一段按字母顺序排列词典的代码。 有没有办法在有序字典中选择第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,但我只想输出键值对的值。)
在Python 2中:
如果要访问密钥:
如果要访问该值:
如果您使用的是Python 3,那么可以通过将
keys
方法返回的KeysView
对象包装为一个列表来进行转换:不是最漂亮的解决方案,但它起作用了。
您需要使用OrderedDict还是只需要支持索引的dict类型?如果是后者,则考虑排序的dict对象。SortedDict(基于密钥排序顺序排序对)的一些实现支持快速n次索引。例如,sortedcontainers项目有一个带有随机访问索引的SortedDict类型。
在你的情况下,它看起来像:
如果您做了大量查找,这将比重复迭代到所需索引快得多。
在这里使用^{} 是有效的,因为为了订阅,我们不必创建任何中间列表。
如果你只想要价值,你可以
相关问题 更多 >
编程相关推荐