简体   繁体   English

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

[英]Iterating ordered dict items starting from specific key

The question is styled in python 2.7 . 这个问题在python 2.7中设计。

I'm using OrderedDict to store some items as follows: 我正在使用OrderedDict存储一些项目,如下所示:

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

( d equals to {'a': 0, 'b': 1, 'c': 2, 'd': 3} ) d等于{'a': 0, 'b': 1, 'c': 2, 'd': 3}

Is there a way iterating dictionary d , starting from specific key? 有没有办法从特定键开始迭代字典d For instance, I'd like to iterate d items starting from key 'b' 例如,我想从键'b'开始迭代d

Many thanks in advance! 提前谢谢了!

You can iterate by looking up the value of b by using items() and slicing off where you need to be. 您可以通过使用items()查找b的值并在需要的位置切片来迭代。 Replace d.keys().index('b') if you have your own way of knowing where you want to start. 如果你有自己的方式知道你想要从哪里开始,请替换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)

Using items() allow you to get the key and value off like normally. 使用items()可以像平常一样关闭键和值。

A solution that works for Python 2 and 3, using itertools.dropwhile() : 使用itertools.dropwhile()适用于Python 2和3的解决方案:

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)

Output: 输出:

b 1
c 2
d 3

Python 2, avoiding the creation of the key-value list with .items() :: Python 2,避免使用.items() ::创建键值列表

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

Timing 定时

%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

Would this work? 这会有用吗?

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

where my_key is the key you want to start from 其中my_key是您要从中开始的键

It seems to me this is one option if you don't want to index a list of tuples: 在我看来,如果您不想索引元组列表,这是一个选项:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM