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. If last is not provided or manually set to True, then the popped value is LIFO (last in, first out). If last is set to False, then the popped value is FIFO.

  • move_to_end(key, last=True): It moves the provided key to the end of the dictionary. If last is set to True, then the key moves to the right. If last is set to False, the key is sent to the front. If the key does not exist, an error is generated.

  • reversed(): Since OrderedDict objects are in order, they can be manipulated like an iterable object; in this case, reverse iteration can be performed on an OrderedDict.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset