Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating ordered dict items starting from specific key

The question is styled in python 2.7 .

I'm using OrderedDict to store some items as follows:

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

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

Is there a way iterating dictionary d, starting from specific key? For instance, I'd like to iterate d items starting from key 'b'

Many thanks in advance!

like image 976
NI6 Avatar asked Oct 19 '25 16:10

NI6


1 Answers

A solution that works for Python 2 and 3, using 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)

Output:

b 1
c 2
d 3

Python 2, avoiding the creation of the key-value list with .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
like image 85
Mike Müller Avatar answered Oct 21 '25 05:10

Mike Müller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!