如何从字典中删除最旧的元素? [英] How to remove the oldest element from a dictionary?
本文介绍了如何从字典中删除最旧的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道删除字典中最旧元素的最佳方法,以便控制最大字典大小.
I would like to know the best way to remove the oldest element in a dictionary in order to control the maximum dictionary size.
示例:
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'}
这清楚吗?
编辑:忘记了len(dict)
落后一项.
推荐答案
字典不保留顺序,因此您无法确定首先添加了哪个元素.您可以将字典与其键列表结合起来以保持顺序.
Dictionaries don't preserve order, so you can't tell which element had been added first. You could combine the dictionary with a list of it's keys to preserve order.
这是 activestate食谱,用于执行此操作的有序字典.
Here's an activestate recipe for an ordered dict that does just this.
还有 PEP-0372 与此
There's also PEP-0372 with this patch for an odict class.
这篇关于如何从字典中删除最旧的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文