Pin*_*ngk 19 python ordereddictionary python-3.x
我有一段代码按字母顺序排序.有没有办法在有序字典中选择第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)])
Run Code Online (Sandbox Code Playgroud)
我希望有一些功能......
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)
Run Code Online (Sandbox Code Playgroud)
怎么能实现这一目标?谢谢.
(类似于在有序指令中访问项目,但我只想输出键值对的值.)
Dan*_*Lee 20
在Python 2中:
如果要访问密钥:
>>> ordered_dict.keys()[2]
'c'
Run Code Online (Sandbox Code Playgroud)
如果想要访问该值:
>>> ordered_dict.values()[2]
2
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Python 3,则可以通过将其包装为列表来转换方法KeysView返回的对象keys:
>>> list(ordered_dict.keys())[2]
'c'
>>> list(ordered_dict.values())[2]
2
Run Code Online (Sandbox Code Playgroud)
不是最漂亮的解决方案,但它确实有效.
the*_*eye 12
itertools.islice在这里使用是有效的,因为我们不必为了下标而创建任何中间列表.
from itertools import islice
print(next(islice(ordered_dict.items(), 2, None)))
Run Code Online (Sandbox Code Playgroud)
如果你只想要价值,你可以做到
print ordered_dict[next(islice(ordered_dict, 2, None))]
Run Code Online (Sandbox Code Playgroud)
你是否必须使用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'
Run Code Online (Sandbox Code Playgroud)
如果你做了很多的查找,这将是一个很多比反复迭代到所需的索引快.
| 归档时间: |
|
| 查看次数: |
14895 次 |
| 最近记录: |