【发布时间】:2014-05-01 21:32:57
【问题描述】:
我有一个按字母顺序排列字典的 sn-p 代码。 有没有办法在有序字典中选择第 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,但我只想输出键值对的值。)
【问题讨论】:
-
试试
ordered_dict[ordered_dict.keys()[index]] -
@IonutHulub,我尝试了(没有用户输入位) print(ordered_dict[ordered_dict.keys()[2]]) 并收到错误,TypeError:“KeysView”对象不支持索引。
-
lambda在b之前写入d。 -
@DanielLee 抱歉,已更正。
-
如果输入是一个小索引,你可以避免对整个
initial字典进行排序,使用heapq:result = initial[heapq.nsmallest(select+1, initial)[-1]]
标签: python python-3.x ordereddictionary