Python字典,具有返回i的查找

2024-04-24 06:11:32 发布

您现在位置:Python中文网/ 问答频道 /正文

<> >我想知道C++的STD::MAP(它是一个排序字典),查找关键字返回一个指向地图中正确位置的迭代器。这意味着您可以查找一个键,然后从该键开始迭代,例如,如果该键实际上是您感兴趣的范围的开始,或者如果您希望“在我的字典中的项就在key之后”。在

有没有其他python dict支持这种功能?在


Tags: key功能map字典排序地图关键字dict
3条回答

在Python2.7+中,可以使用OrderedDict:

import collections
import itertools

foo=collections.OrderedDict((('a',1),('b',2),('c',3)))
for key,value in itertools.dropwhile(lambda x: x[0]!='b',foo.iteritems()):
    print(key,value)

收益率

^{pr2}$

对于Python2.6或更低版本,可以使用OrderedDict recipe。在

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

print my_dict

keys = my_dict.keys()
keys.sort()
start_index = keys.index('b')

for key in keys[start_index:]:
    print key, my_dict[key]

================================

{'a':1,'c':3,'b':2,'d':4}

乙2

丙3

第4天

相关问题 更多 >