问题是在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'
个项目
非常感谢提前!
答案 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)