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