Matching by dict values ​​for Python?

I'm interested in an implementation dictfor Python that provides an iterative interface for sorted values. Ie, a dictwith the function " sortedvalues()".

It’s naive to do sorted(dict.values()), but that’s not what I want. Each time items are inserted or deleted, you need to perform a complete sort, which is inefficient.

Note that I am not asking about key-sorted dict either (for this question there are excellent answers in Key-ordered dict in Python and Python 2.6 TreeMap / SortedDictionary? ).

+3
source share
4 answers

, , . - , , . , . , .

, , , .

: , , :

  • dict -

  • , , bisect

: . - . , , ( ) .

, (, ) b.

2. :

import bisect
class dictvs(dict):
    def __init__(self):
        self._list = []

    def __setitem__(self, key, value):
        old = self.get(key)
        if old is None:
            bisect.insort(self._list, value)
            dict.__setitem__(self, key, value)
        else:
            oldpos = bisect.bisect_left(self._list, old)
            newpos = bisect.bisect_left(self._list, value)
            if newpos > oldpos:
                newpos -= 1
                for i in xrange(oldpos, newpos):
                    self._list[i] = self._list[i + 1]
            else:
                for i in xrange(oldpos, newpos, -1):
                    self._list[i] = self._list[i - 1]
            self._list[newpos] = value
            dict.__setitem__(self, key, value)

    def __delitem__(self, key):
        old = self.get(key)
        if old is not None:
            oldpos = bisect.bisect(self._list, old)
            del self._list[oldpos]
        dict.__delitem__(self, key)

    def values(self):
        return list(self._list)

dict, . . unit test values() sorted(dict.values(instance)) . , , bisect

+2

, dict, , (sorted_keys), () (sorted_values).

__setitem__(), bisect, k, (, ) ​​ . , , , sorted_values[k:k] = [new_value] sorted_keys[k:k] = [new_key]; , O(n) (so O(n^2) ).

heapq (value, key). O(log n) .

(sorted_keys), .

, , ( ), ( , ) .

+3

, :

  • , dict.
  • : , ; .

In the commentary, we note that sorting lists that are sorted almost quickly, so this approach should be pretty quick.

+2
source

You can use skip dict . This is a Python dictionary that is constantly sorted by value.

Inserting is a bit more expensive than a regular dictionary, but it's worth it if you often need to iterate in order or execute queries based on values, such as:

  • What is the highest / lowest element?
  • What elements matter between X and Y?
+1
source

All Articles