Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 393
João Portela Avatar asked Nov 18 '09 15:11

João Portela


People also ask

How do you remove the first key-value pair in a dictionary?

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.

How do I remove the last element from a dictionary?

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.

How do you remove an attribute from a dictionary?

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.


2 Answers

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, ...

like image 165
Adrien Plisson Avatar answered Oct 05 '22 09:10

Adrien Plisson


Python dictionaries are ordered now (from 3.6 and above). more details
next(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)))
like image 30
lulu Avatar answered Oct 05 '22 10:10

lulu