I have an OrderedDict
in and I have two keys. I know that one key is stored before the other key and I would like to iterate all items between the first key to the second key.
I don't want to iterate over the whole map, because it's huge. Only the items between the two keys I have. How can I do this?
CodePudding user response:
You could use a pandas Series in place of the dict. pandas is a huge dependency though.
>>> import pandas as pd
>>> d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> s = pd.Series(d)
>>> s['b':'d']
b 2
c 3
d 4
dtype: int64
>>> s['b':'d'].to_dict()
{'b': 2, 'c': 3, 'd': 4}
(Demo is with a regular dict because they are ordered with respect to key insertion since Python 3.7.)
CodePudding user response:
You can use slice of Ordered Dictionary like:
# let d be you Ordered Dictionary.
first_index = d.keys().index(key1)
second_index = d.keys().index(key2)
print(d[first_index:second_index 1])