代码之家  ›  专栏  ›  技术社区  ›  NI6

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

  •  3
  • NI6  · 技术社区  · 8 年前

    这个问题是在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 回复  |  直到 8 年前
        1
  •  3
  •   Mike Müller    8 年前

    一个适用于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
  •  2
  •   MooingRawr    8 年前

    您可以通过查找 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)
    

    使用 项目() 允许您像往常一样关闭键和值。

        3
  •  0
  •   jpp    8 年前

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

    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)
    
        4
  •  -1
  •   omu_negru    8 年前

    这样行吗?

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

    哪里 my_key 是要从中开始的关键点