Python OrderedDict with Examples

Python OrderedDict is a dict subclass that maintains the items insertion order. When we iterate over an OrderedDict, items are returned in the order they were inserted.

A regular dictionary doesn’t track the insertion order. So when iterating over it, items are returned in an arbitrary order. When we want to make sure that items are returned in the order they were inserted, we can use OrderedDict.

Python OrderedDict

  • OrderedDict is part of python collections module.
  • We can create an empty OrderedDict and add items to it. If we create an OrderedDict by passing a dict argument, then the ordering may be lost because dict doesn’t maintain the insertion order.
  • If an item is overwritten in the OrderedDict, it’s position is maintained.
  • If an item is deleted and added again, then it moves to the last.
  • OrderedDict popitem removes the items in FIFO order. It accepts a boolean argument last, if it’s set to True then items are returned in LIFO order.
  • We can move an item to the beginning or end of the OrderedDict using move_to_end function. It accepts a boolean argument last, if it’s set to False then item is moved to the start of the ordered dict.
  • From python 3.6 onwards, order is retained for keyword arguments passed to the OrderedDict constructor, refer PEP-468.
  • We can use reversed() function with OrderedDict to iterate elements in the reverse order.
  • Equality tests between OrderedDict objects are order-sensitive and are implemented as list(od1.items())==list(od2.items()).
  • Equality tests between OrderedDict and other Mapping objects are order-insensitive like regular dictionaries. This allows OrderedDict objects to be substituted anywhere a regular dictionary is used.

Python OrderedDict Examples

Let’s look at some code examples of Python OrderedDict.

Creating OrderedDict object

Output:

Adding, Replacing, Removing items from OrderedDict

Output:

OrderedDict move_to_end example

Output:

OrderedDict popitem example

Output:

OrderedDict Reverse Iteration

Output:

OrderedDict Equality Tests Example

Output:

Reference: Python Docs

By admin

Leave a Reply

%d bloggers like this: