I'm implementing something like a cache, which works like this:
- If a new value for the given key arrives from some external process, store that value, and remember the time when this value arrived.
- If we are idle, find the oldest entry in the cache, fetch the new value for the key from external source and update the cache.
- Return the value for the given key when asked.
I need a data structure to store key-value pairs which would allow to perform the following operations as fast as possible (in the order of speed priority):
- Find the key with the lowest (unknown) value.
- Update a value for the given key or add a new key-value pair if the key does not exist.
- Other regular hash-table operations, like delete a key, check if a key exists, etc.
Are there any data-structures which allow this? The problem here is that to perform the first query quickly I need something value-ordered and to update the values for the given key quickly I need something key-ordered. The best solution I have so far is something like this:
Store values an a regular hashtable, and pairs of (value, key) as a value-ordered heap. Finding the key for the lowest value goes like this:
- Find the key for the lowest value on the heap.
- Find the value for that key from the hashtable.
- If the values don't match pop the value from the heap and repeat from step 1.
Updating the values goes like this:
- Store the value in the hashtable.
- Push the new (value, key) pair to the heap.
Deleting a key is more tricky and requires searching for the value in the heap. This gives something like O(log n) performance, but this solution seems to be cumbersome to me.
Are there any data structures which combine the properties of a hashtable for keys and a heap for the associated values? I'm programming in Python, so if there are existing implementations in Python, it is a big plus.