I needed a way to append an item to an
OrderedDict, without creating a new object (too consuming) and I stumbled upon this answer on StackOverflow.
The answer gives a solution to the inverse problem (that is, prepending an item), but was good enough to be modified for my situation, without me needing to delve too much into the details of the OrderedDict data structure (it’s basically a linked list, under the hood).
Enough said, here it is for future reference:
class MyOrderedDict(OrderedDict): def append(self, key, value): root = self._OrderedDict__root last = root if key in self: raise KeyError else: root = last = self._OrderedDict__map[key] = [last, root, key] dict.__setitem__(self, key, value)