How do I efficiently get the index and value for a key from SortedDict?

508 Views Asked by At

Given a collection that is ordered and keyed (like OrderedDict or SortedContainers SortedDict) I want to do the following:

d['first'] = 'hi'
d['second'] = 'there'
d['third'] = 'world'
(ix, value) = d.get_index_and_value('second')
assert d.iloc[ix + 1] == 'third'
# or list(d.keys())[ix + 1] with OrderedDict

however I cannot see an efficient way to get both the index and the value given a key ((ix, value) = d.get_index_and_value('second')).

Is this possible with SortedDict, or another container?

In practice, my keys are a sortable collection (dates) if that means there is a better container I could use.

1

There are 1 best solutions below

1
On

You can use the index method of keys:

ix, value = d.keys().index('second'), d['second']

this will return

(1, 'there')

If you don't want to repeat yourself, you can make this a function, or extend OrderedDict to include this as a method:

def get_index_and_value(d, key):
    return d.keys().index(key), d[key]

print(get_index_and_value(d, 'second')