I am interested in a dict implementation for Python that provides an iterating interface to sorted values. I.e., a dict with a “sortedvalues()” function.
Naively one can do sorted(dict.values()) but that’s not what I want. Every time items are inserted or deleted, one has to run a full sorting which isn’t efficient.
Note that I am not asking about key-sorted dict either (for that question, there are excellent answers in Key-ordered dict in Python and Python 2.6 TreeMap/SortedDictionary?).
The problem is that you need to sort or hash it by keys to get reasonable insert and lookup performance. A naive way of implementing it would be a value-sorted tree structure of entries, and a dict to lookup the tree position for a key. You need to get deep into updating the tree though, as this lookup dictionary needs to be kept correct. Essentially, as you would do for an updatable heap.
I figure there are too many options to make a resonable standard library option out of such a structure, while it is too rarely needed.
Update: a trick that might work for you is to use a dual structure:
a regular
dictstoring the key-value pairs as usualany kind of sorted list, for example using
bisectThen you have to implement the common operations on both: a new value is inserted into both structures. The tricky part are the update and delete operations. You use the first structure to look up the old value, delete the old value from the second structure, then (when updating) reinsert as before.
If you need to know the keys too, store (value, key) pairs in your b list.
Update 2: Try this class:
It’s not a complete
dictyet I guess. I havn’t tested deletions, and just a tiny update set. You should make a larger unit test for it, and compare the return ofvalues()with that ofsorted(dict.values(instance))there. This is just to show how to update the sorted list withbisect