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

时间:2018-03-08 16:24:37

标签: python python-2.7 dictionary slice

问题是在python 2.7中设置的。

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

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

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

有没有办法从特定键开始迭代字典d? 例如,我想从密钥d

开始迭代'b'个项目

非常感谢提前!

4 个答案:

答案 0 :(得分:3)

您可以通过使用b查找items()的值来进行迭代,然后切换到您需要的位置。如果您有自己的方式知道自己想要开始的地方,请替换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()可以让您像往常一样获取密钥和值。

答案 1 :(得分:3)

适用于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)

输出:

b 1
c 2
d 3

Python 2,避免使用.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

答案 2 :(得分:0)

这会有用吗?

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

其中my_key是您要从

开始的键

答案 3 :(得分:0)

在我看来,如果您不想索引元组列表,这是一个选项:

from collections import OrderedDict
from itertools import islice

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

for each in islice(d.iteritems(), d.keys().index('b'), None):
    print(each)