python - 从特定键开始迭代有序的字典项

标签 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? 例如,我想从键 'b'

开始迭代 d

非常感谢!

最佳答案

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

关于python - 从特定键开始迭代有序的字典项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49177869/

相关文章:

python - 最佳实践 : how do you list required dependencies in your setup. py?

python-2.7 - 从 Python NLTK 或其他模块中的任何单词中获取音素?

python - 如何在多个文件上运行 python 脚本以获得多个输出文件?

python - python中带有字典的if else语句

python - Django聚合

python - Tkinter : How to bind parentheses key

python - 在python中随机打乱一个稀疏矩阵

python-2.7 - python中的双点运算符(..)是什么?

swift - 如何正确使用词典收藏?

c# - Dictionary of Dictionaries的扩展方法