I would like to know the best way to remove the oldest element in a dictionary in order to control the maximum dictionary size.
example:
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'}
Was this clear?
Edit: Forgot that len(dict)
lags one item behind.
Because key-value pairs in dictionaries are objects, you can delete them using the “del” keyword. The “del” keyword is used to delete a key that does exist. It raises a KeyError if a key is not present in a dictionary. We use the indexing notation to retrieve the item from the dictionary we want to remove.
The popitem() method removes the item that was last inserted into the dictionary. In versions before 3.7, the popitem() method removes a random item.
In order to remove the read-only attribute from those files you have to remove the other attributes as well (for example attrib -h -r ). Page at that link no longer exists. cd /d "path" & attrib -r "%cd%\*" /s can be used from current directory if required. Also as Daniel has said, wrap the path with one " either side.
Python 3.1 has an ordered dict. use the class collections.OrderedDict
to keep the elements in their order of insertions. beware that if you are overwriting an element, it keeps its place in the order, you need to delete and re-insert an element to make it last.
if you are using an older release, a patch may be available to get OrderedDict.
anyway, if it is not available, you may simply use a list of tuples: it can be easily converted to and from a dictionary, keeps its ordering, can be used like a queue with append
and pop
, ...
Python dictionaries are ordered now (from 3.6 and above). more detailsnext(iter(dict))
would give the oldest (or first) key. stackoverflow answer
So to delete oldest (or first) key, we can use the following...
dict.pop(next(iter(dict)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With