我想知道删除字典中最旧的元素以控制字典大小的最佳方法.
例如:
MAXSIZE = 4
dict = {}
def add(key,value):
if len(dict) == MAXSIZE:
old = get_oldest_key() # returns the key to the oldest item
del dict[old]
dict[key] = value
add('a','1') # {'a': '1'}
add('b','2') # {'a': '1', 'b': '2'}
add('c','3') # {'a': '1', 'c': '3', 'b': '2'}
add('d','4') # {'a': '1', 'c': '3', 'b': '2', 'd': '4'}
add('e','5') # {'c': '3', 'b': '2', 'e': '5', 'd': '4'}
Run Code Online (Sandbox Code Playgroud)
这个清楚了吗?
编辑:忘了len(dict)落后一项.
Adr*_*son 12
Python 3.1有一个有序的字典.使用该类collections.OrderedDict来保持元素的插入顺序.请注意,如果要覆盖一个元素,它会按顺序保留其位置,则需要删除并重新插入一个元素以使其最后.
如果您使用的是旧版本,则可以使用补丁来获取OrderedDict.
无论如何,如果它不可用,你可以简单地使用一个元组列表:它可以很容易地从字典转换成字典,保持其顺序,可以像append和队列一样使用,和pop......
小智 6
现在订购 Python 词典(从 3.6 及更高版本开始)。更多细节
next(iter(dict))将给出最旧的(或第一个)键。堆栈溢出答案
所以要删除最旧的(或第一个)键,我们可以使用以下...
dict.pop(next(iter(dict)))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5177 次 |
| 最近记录: |