views:

317

answers:

4

I'd like to work with a dict in python, but limit the number of key/value pairs to X. In other words, if the dict is currently storing X key/value pairs and I perform an insertion, I would like one of the existing pairs to be dropped. It would be nice if it was the least recently inserted/accesses key but that's not completely necessary.

If this exists in the standard library please save me some time and point it out!

+1  A: 

You can create a custom dictionary class by subclassing dict. In your case, you would have to override __setitem__ to have check your own length and delete something if the limit is recahed. The following example would print the current lenght after every insertion:

class mydict(dict):
    def __setitem__(self, k, v):
        dict.__setitem__(self, k, v)
        print len(self)

d = mydict()
d['foo'] = 'bar'
d['bar'] = 'baz'
Chris089
Subclassing builtins like `dict` is often fruitless. In normal circumstances with subclassing, methods like `update` and `setdefault` would rely on the overrided `__getitem__`, but this is not how it works here. Subclassing builtins makes it easy to introduce difficult-to-see bugs. When you eliminate all such bugs, you really haven't saved any work by subclassing.
Mike Graham
Interesting. Could you show an example of such an bug?
Chris089
+1  A: 

A dict does not have this behavior. You could make your own class that does this, for example something like

class MaxSizeDict(object):
    def __init__(self, max_size):
        self.max_size = max_size
        self.dict = {}
    def __setitem__(self, key, value):
        if key in self.dict:
            self.dict[key] = value    
            return

        if len(self.dict) >= self.max_size:
      ...

A few notes about this

  • It would be tempting for some to subclass dict here. You can technically do this, but it is bug-prone because the methods do not depend on each other. You can use UserDict.DictMixin to save having to define all methods. There are few methods you would be able re-use if you subclass dict.
  • A dict does not know what the least recently added key is, since dicts are unordered.
    • 2.7 will introduce collections.OrderedDict, but for now keeping the keys in order separately should work fine (use a collections.deque as a queue).
    • If getting the oldest isn't all that imporant, you can just use the popitem method to delete one arbitrary item.
  • I interprettered oldest to mean first insertion, approximately. You would have to do something a bit different to eliminate the LRU items. The most obvious efficient strategy would involve keeping a doubly-linked list of keys with references to the nodes themselves stored as dict values (along with the real values). This gets more complicated and implementing it in pure Python carries a lot of overhead.
Mike Graham
You actually need something much more complex than a dict+deque if you want O(1) get-/set-/delitem, though of course this only really matters for larger sizes.
Roger Pate
You can directly reuse about half of the methods from the dict, OrderedDict, or other base even without using DictMixin. It really doesn't seem that bugprone to write forwarding methods for the others, certainly no more bugprone than having to write them all yourself, as you have here.
Roger Pate
I am trying to get at what hopefully solves the problem at hand. dict+deque gives you O(1) get, set, and delitem if you only care a little about the orderedness of the keys and you don't fall into the pathological case where there are many deletions and re-setting of the same keys, leading to the deque being polluted by keys not in the dict.
Mike Graham
No, for delitem you have to search the deque for the deleted item, and that's O(n). Check out one of the pure-Python OrderedDict implementations.
Roger Pate
The majority of the times I've seen `dict` subclassed in the wild, the coder forgot to override all the appropriate methods. This means that errors stemming from this have the opportunity to pass silently, which is really bad. I really don't see much to be gained from subclassing in a case like this.
Mike Graham
So think about what you're doing and write some tests, same as when writing anything. Sloppy code will always have bugs.
Roger Pate
If you wanted the current keys stored, you'd have to search the deque or list or whatever. However, if you leave the item there and when you pop it verify whether it is in the dict, you save the search. Whether this scales or not depends on how the instances are being used.
Mike Graham
Like I say, I don't see much benefit to subclassing here to start with. I do think that it ends up introducing a danger—things that look like they *should* work and that *would* work when subclassing a Python class will not work. I would need to see some real benefit to want to introduce something like that to code I was maintaining.
Mike Graham
Assuming update calls getitem without knowing or checking is sloppy any way you slice it, and that assumption is the only way to "look like [it] should work". You never know if you have missing functionality or not *unless you test or otherwise prove everything you want to guarantee*. -- Again, look at one of the decent pure-Python OrderedDict implementations, which do have O(1) delitem.
Roger Pate
Deleting the keys from the left of the deque and sacrificing some correctness, I am not necessarily performing an O(n) operation to delete the items being eliminated.
Mike Graham
_"2.7 will introduce collections.OrderedDict"_ Python 3.1 already has OrderedDict. time for a change ?
Adrien Plisson
Very, very few people are using 3.x for writing serious code currently because of the lack of support by important libraries like numpy, PIL, twisted, and most of the web frameworks and because of the cost of porting code bases. (Especially the former reason.)
Mike Graham
@Mike: When I say delitem, I mean `__delitem__`, as in `del d[key]`. Note this O(n) search really does matter if he wants to use LRU instead of LR-added.
Roger Pate
@Adrien: 3.x is a split from 2.x and development is happening in parallel with 2.x, rather than 3.x being "later". It's correct to say 2.7 and 3.1 both introduce it to their respective lines.
Roger Pate
@Roger, I haven't defined what I need to do for that operation, if OP needs to support it at all. You do not have to do the O(n) search/delete on the deque/list if you don't *need* to maintain a container of the current keys like you must in an ordered dict type.
Mike Graham
@Roger: i am perfectly aware of this fact. i am just trying to convince the most people to switch to python 3.
Adrien Plisson
@Mike: ...and because libraries are lacking python 3 support, people do not use it for serious development, and we are back at the starting point. if we continue this way, people will still be using python 2 in 20 years (like people are still using C89 nowadays).
Adrien Plisson
The (not-that-scary) threat of people sticking with Python 2 in the long term does not make switching more feasible for people that need an efficient numerical math library, a web framework, a great asynchronous networking library, or a way to manipulate images.
Mike Graham
+4  A: 

Python 2.7 and 3.1 have OrderedDict and there are pure-Python implementations for earlier Pythons.

class LimitedSizeDict(OrderedDict):
  def __init__(self, *args, **kwds):
    self.size_limit = kwds.pop("size_limit", None)
    OrderedDict.__init__(self, *args, **kwds)
    self._check_size_limit()

  def __setitem__(self, key, value):
    OrderedDict.__setitem__(self, key, value)
    self._check_size_limit()

  def _check_size_limit(self):
    if self.size_limit is not None:
      while len(self) > self.size_limit:
        self.popitem(last=False)

You would also have to override other methods that can insert items, such as update. The primary use of OrderedDict is so you can control what gets popped easily, otherwise a normal dict would work.

Roger Pate
@Mike: `(self, size_limit=None, *args, **kwds)` is wrong and keyword-only parameters (`(self, *args, size_limit=None, **kwds)`) aren't in current 2.x. (Are they being considered for 2.7? Regardless they aren't 2.6.) This code works with just about any version the OP is likely to use, makes *size\_limit* effectively a keyword-only parameter, and maintains the same interface as dicts.
Roger Pate
Have you tested your code on Python 2.7? `dict.pop` requires at least 1 argument. `dict.popitem()` works, but it removed the recent item.
Sridhar Ratnakumar
Also, __setitem__ should check for size limit *before* actually setting the item, lest you end up losing the very item your are setting!
Sridhar Ratnakumar
@Sridhar: Looking at it now, months later, I'm not sure what I was thinking; but popitem makes more sense.
Roger Pate
@Sridhar: You need to check after setting the item, as you might be replacing an existing item.
Roger Pate
+2  A: 

Here's a simple, no-LRU Python 2.6+ solution (in older Pythons you could do something similar with UserDict.DictMixin, but in 2.6 and better that's not recommended, and the ABCs from collections are preferable anyway...):

import collections

class MyDict(collections.MutableMapping):
  def __init__(self, maxlen, *a, **k):
    self.maxlen = maxlen
    self.d = dict(*a, **k)
    while len(self) > maxlen:
      self.popitem()
  def __iter__(self):
    return iter(self.d)
  def __len__(self):
    return len(self.d)
  def __getitem__(self, k):
    return self.d[k]
  def __delitem__(self, k):
    del self.d[k]
  def __setitem__(self, k, v):
    if k not in self and len(self) == self.maxlen:
      self.popitem()
    self.d[k] = v 

d = MyDict(5)
for i in range(10):
  d[i] = i
  print sorted(d)

As other answers mentioned, you probably don't want to subclass dict -- the explicit delegation to self.d is unfortunately boilerplatey but it does guarantee that every other method is properly supplied by collections.MutableDict.

Alex Martelli