Key-ordered dict in Python

前端 未结 10 2199
北恋
北恋 2020-11-28 05:14

I am looking for a solid implementation of an ordered associative array, that is, an ordered dictionary. I want the ordering in terms of keys, not of insertion order.

10条回答
  •  难免孤独
    2020-11-28 05:44

    Here is my own implementation:

    import bisect
    class KeyOrderedDict(object):
       __slots__ = ['d', 'l']
       def __init__(self, *args, **kwargs):
          self.l = sorted(kwargs)
          self.d = kwargs
    
       def __setitem__(self, k, v):
          if not k in self.d:
             idx = bisect.bisect(self.l, k)
             self.l.insert(idx, k)
           self.d[k] = v
    
       def __getitem__(self, k):
          return self.d[k]
    
       def __delitem__(self, k):
          idx = bisect.bisect_left(self.l, k)
          del self.l[idx]
          del self.d[k]
    
       def __iter__(self):
          return iter(self.l)
    
       def __contains__(self, k):
          return k in self.d
    

    The use of bisect keeps self.l ordered, and insertion is O(n) (because of the insert, but not a killer in my case, because I append far more often than truly insert, so the usual case is amortized O(1)). Access is O(1), and iteration O(n). But maybe someone had invented (in C) something with a more clever structure ?

提交回复
热议问题