限制一个python字典的大小 [英] Limiting the size of a python dictionary

查看:923
本文介绍了限制一个python字典的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python中使用dict,但是将键/值对的数量限制为X.换句话说,如果dict正在存储X键/值对,并且我执行插入,我将像现有的一对被丢弃。如果它是最近插入/访问密钥最少,那将是很好的。但是这并不完全是必要的。



如果这个标准库存在,请给我一些时间点出来!

解决方案

Python 2.7和3.1有 OrderedDict ,并且有较早的Pythons的纯Python实现。

  from collections import OrderedDict 

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,值)
OrderedDict .__ setitem __(self,key,value)
self._check_size_limit()

def _check_size_limit(self):
如果self.size_limit不是无:
,而len (自)> self.size_limit:
self.popitem(last = False)

您还必须覆盖可以插入项目的其他方法,如更新。 OrderedDict的主要用途是,您可以控制易于弹出的内容,否则正常的字体可以正常工作。


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!

解决方案

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

from collections import OrderedDict

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.

这篇关于限制一个python字典的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆