我有一段代码,按字母顺序对字典进行排序。
有没有办法在有序字典中选择第i个键并返回其对应的值?即

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中:

如果要访问密钥:

>>> ordered_dict = OrderedDict([('a', 1), ('b', 2), ('c', 2), ('d', 1), ('e', 3)])
>>> ordered_dict.keys()[2]
'c'

如果要访问该值:
>>> ordered_dict.values()[2]
2

如果您使用的是Python 3,则可以将KeysView方法返回的keys对象包装为列表,以将其转换:
>>> list(ordered_dict.keys())[2]
'c'
>>> list(ordered_dict.values())[2]
2

不是最漂亮的解决方案,但它可以工作。

关于python - Python在OrderedDict中选择第i个元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22610896/

10-14 19:04
查看更多