从特定键开始迭代有序dict项

2024-04-20 00:33:59 发布

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

这个问题是用python2.7设计的。在

我使用OrderedDict来存储一些项目,如下所示:

d = OrderedDict(zip(['a', 'b', 'c', 'd'], range(4)))

d等于{'a': 0, 'b': 1, 'c': 2, 'd': 3}

有没有办法从特定的键开始迭代dictionary d? 例如,我想从键'b'开始迭代d

先谢谢你!在


Tags: 项目dictionaryrangezipordereddict办法
3条回答

您可以通过使用items()查找b的值并在需要的地方进行切片来进行迭代。如果您有自己的方法知道要从哪里开始,请替换d.keys().index('b')。在

from collections import OrderedDict

d = OrderedDict(zip(['a', 'b', 'c', 'd'], range(4)))

for each in d.items()[d.keys().index('b'):]:
    print(each)

使用items()可以像平常一样获取键和值。在

一个适用于Python 2和3的解决方案,使用itertools.dropwhile()

from __future__ import print_function

from collections import OrderedDict
from itertools import dropwhile

d = OrderedDict(zip(['a', 'b', 'c', 'd'], range(4)))

for k, v in dropwhile(lambda x: x[0] != 'b', d.items()):
    print(k, v)

输出:

^{pr2}$

Python2,避免使用.items()创建键值列表:

for k, v in dropwhile(lambda x: x[0] != 'b', d.iteritems()):
    print(k, v)

定时

%timeit
for each in d.items()[d.keys().index('b'):]:
    pass
The slowest run took 5.18 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 3.27 µs per loop

%%timeit
for each in islice(d.iteritems(), d.keys().index('b'), None):
    pass
The slowest run took 5.23 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 3.05 µs per loop

%%timeit
for k, v in dropwhile(lambda x: x[0] != 'b', d.iteritems()):
    pass
The slowest run took 4.92 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.23 µs per loop

这样行吗?在

for x in list(a.keys())[a.index(my_key):]:
    print(a[x])

其中my_key是您要从中开始的键

相关问题 更多 >