MisterMe
MisterMe

Reputation: 159

Python. Iterating dictionary starting from certain key

Let's say I have a dictionary:

{"a": 1, "b": 2, "h": 55 }

Is there any way to iterate through the dictionary, starting from the "b" key?

Upvotes: 1

Views: 1669

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121834

Dictionaries have no order; but if you expected alphabetical ordering you can sort the keys and skip until you get to the 'b' key with itertools.dropwhile():

from itertools import dropwhile

for key in dropwhile(lambda k: k != 'b', sorted(your_dictionary)):

Demo:

>>> from itertools import dropwhile
>>> d = {"a": 1, "b": 2, "h": 55 }
>>> for key in dropwhile(lambda k: k != 'b', sorted(d)):
...     print key, d[key]
... 
b 2
h 55

Even if you were using a collections.OrderedDict() object (which preserves insertion order), you'd still have to skip over the keys until you got to your 'starter' key.

Upvotes: 7

Related Questions