在OrderedDict中选择第i个元素

21 投票
5 回答
25322 浏览
提问于 2025-04-17 23:39

我有一段代码,可以把字典按字母顺序排列。请问有没有办法选择排好序的字典中的第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)

这个怎么实现呢?谢谢。

(类似于 访问有序字典中的项目,但我只想输出键值对中的值。)

5 个回答

0

别小看了这个普通的for循环:

from collections import OrderedDict

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

def ith(od, tgt):
    for i, t in enumerate(od.items()):
        if i==tgt:
            print('element {}\'s key is "{}"'.format(i,t[0]))
            break
    else:
        print('element {} not found'.format(tgt)) 

ith(od, 2)
# element 2's key is "c"
ith(od, 20) 
# element 20 not found

它的好处是,一旦找到想要的元素,循环就会立刻停止。如果没有找到,它也会返回一个合理的结果...

不过,它的缺点是,不支持相对切片。

1

你可以按照这样的方式来做(od 是有序字典):

def get_idx(od, idx):
   from itertools import islice
   idx = (idx + len(od)) % len(od)
   t = islice(od.items(), idx, idx + 1)
   return next(t)

>>>x

OrderedDict([('a', 2), ('b', 3), ('k', 23), ('t', 41), ('q', 23)])

>>>get_idx(x, 1)
('b', 3)
>>>get_idx(x, 2)
('k', 23)
>>>get_idx(x, 4)
('q', 23)
>>>get_idx(x, -1)
('q', 23)
>>>get_idx(x, -2)
('t', 41)
6

你是想用一个有序字典(OrderedDict),还是只想要一个像字典一样的东西,但能支持索引?如果是后者,可以考虑使用一个排序字典对象。有些排序字典的实现(SortedDict)是根据键的顺序来排列的,并且支持快速的索引访问。例如,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'

如果你需要频繁查找,这样做会比一次次循环到你想要的索引快很多

12

这里使用 itertools.islice 是很有效的,因为我们不需要为了获取某些元素而创建额外的列表。

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

如果你只想要一个值,可以这样做:

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

在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,可以通过把keys方法返回的KeysView对象包裹成一个列表来转换它:

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

虽然这个方法不是最优雅的,但它确实能用。

撰写回答