Implementing OrderedDict
Like Counter
, the OrderedDict
is a dictionary subclass the doesn't randomize the order of dictionary items. As items are added to the OrderedDict
, it remembers the order that the keys were inserted and maintains that order. Even if a new entry overwrites an existing key, the position within the dictionary doesn't change. However, if an entry is deleted, re-inserting it will place it at the end of the dictionary.
OrderedDict
, being a subclasses of dict
, inherit all the methods available to dictionaries. There are also three special methods available to OrderedDict
:
popitem(last=True)
: It returns and removes the key:value pair at the end of the dictionary. Iflast
is not provided or manually set toTrue
, then the popped value is LIFO (last in, first out). Iflast
is set toFalse
, then the popped value is FIFO.move_to_end(key, last=True)
: It moves the provided key to the end of the dictionary. Iflast
is set toTrue
, then the key moves to the right. Iflast
is set to...