Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First key in OrderedDict that exceeds threshold

Say I have an OrderedDict:

a = OrderedDict([(5, 'a'), (7, 'b'), (10, 'c')])

Is there an efficient way to get the first value whose key exceeds a certain threshold, without looping over all keys?

Examples:

>>> get_first(a, 6)
'a'
>>> get_first(a, 3)
None
>>> get_first(a, 8)
'b'

I would like to avoid having to implement binary search myself. Is there an efficient out-of-the-box implementation available?

like image 352
user3446746 Avatar asked Jan 23 '26 21:01

user3446746


1 Answers

You don't have to implement a binary search yourself, you can use the bisect for that. However, OrderedDict is not sorted so you can't use a binary search on the dictionary keys unless you sort them first, and that won't be very efficient (in fact it's likely to be faster to just loop over the keys).

If you maintain a sorted list of keys, then that could work, or if you use an implementation of a dictionary that is sorted. You can use the built-in collections.OrderedDict but then you would have to maintain the sorting yourself, or you can use some btree implementation, I think there are several.

I have only used BTree, it's written in C and very fast, but the API is somewhat obtuse.

like image 161
Lennart Regebro Avatar answered Jan 26 '26 13:01

Lennart Regebro