如何限制字典的大小?
我想在 python 中使用字典,但将键/值对的数量限制为 X。换句话说,如果字典当前存储 X 个键/值对并且我执行插入,我想要以下之一要删除的现有对。如果它是最近最少插入/访问的密钥,那就太好了,但这并不是完全必要的。
如果标准库中存在这个,请节省我一些时间并指出它!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
Python 2.7 和 3.1 有 OrderedDict 并且有纯 Python 实现对于早期的Python。
您还必须重写其他可以插入项目的方法,例如
update
。OrderedDict
的主要用途是让您可以轻松控制弹出的内容,否则普通的dict
就可以工作。Python 2.7 and 3.1 have OrderedDict and there are pure-Python implementations for earlier Pythons.
You would also have to override other methods that can insert items, such as
update
. The primary use ofOrderedDict
is so you can control what gets popped easily, otherwise a normaldict
would work.cachetools 将为您提供映射哈希的良好实现来执行此操作(并且它适用于 python 2 和 3) )。
文档摘录:
cachetools will provide you nice implementation of Mapping Hashes that does this (and it works on python 2 and 3).
Excerpt of the documentation:
这是一个简单的、无 LRU Python 2.6+ 解决方案(在较旧的 Python 中,您可以使用
UserDict.DictMixin
执行类似的操作,但在 2.6 及更高版本中不建议这样做,并且来自collections< 的 ABC /code> 无论如何都是更好的...):
正如其他答案提到的,您可能不想子类 dict —— 不幸的是,显式委托给
self.d
是样板文件,但它确实保证每一个其他方法都由collections.MutableMapping
正确提供。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 fromcollections
are preferable anyway...):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 bycollections.MutableMapping
.这是一个简单而高效的 LRU 缓存,用非常简单的 Python 代码编写,可以在任何 python 版本 1.5.2 或更高版本上运行:
Here is a simple and efficient LRU cache written with dirt simple Python code that runs on any python version 1.5.2 or later:
有很多好的答案,但我想指出一个简单的、Pythonic 的 LRU 缓存实现。这与亚历克斯·马尔泰利的回答类似。
There have been many good answers, but I want to point out a simple, pythonic implementation for LRU cache. It's similar to Alex Martelli's answer.
您可以通过子类化 dict 来创建自定义字典类。在您的情况下,您必须覆盖
__setitem__
来检查您自己的长度,并在重新缓存限制时删除某些内容。以下示例将在每次插入后打印当前长度: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:字典没有这种行为。您可以创建自己的类来执行此操作,例如类似“
有关此的一些注释”之类的内容,
dict
。从技术上讲,您可以做到这一点,但它很容易出现错误,因为这些方法不相互依赖。您可以使用 UserDict.DictMixin 来避免定义所有方法。如果您对dict
进行子类化,那么您可以重用的方法很少。collections.OrderedDict
,但目前单独保持键的顺序应该可以正常工作(使用collections.deque
作为队列)。popitem
方法删除任意一项。A dict does not have this behavior. You could make your own class that does this, for example something like
A few notes about this
dict
here. You can technically do this, but it is bug-prone because the methods do not depend on each other. You can useUserDict.DictMixin
to save having to define all methods. There are few methods you would be able re-use if you subclassdict
.collections.OrderedDict
, but for now keeping the keys in order separately should work fine (use acollections.deque
as a queue).popitem
method to delete one arbitrary item.有一个名为 CircularDict 的库实现了此行为。它允许限制 dict 可以存储的最大项目数量,还可以设置内存使用限制。
它可以安装:
并以这种方式使用:
输出将如下所示。
There is a library called CircularDict that implements this behaviour. It allows to limit the maximum amount of items the
dict
can store, but also to set memory usage limits.It can be installed with:
And used this way:
Ouptut will look like.