OrderedDict objects in Python
Do not miss this exclusive book on Binary Tree Problems. Get it now for free.
Reading time: 15 minutes | Coding time: 5 minutes
An ordereddict is a subclass of the dictionary object in Python.
A dictionary stores items which are values associated with a key. They are called key: value pairs where a key can be used to retrieve its paired value. Within one dictionary, keys should be unique as to differentiate each key: value pair.
ordereddicts have certain advantages when compared to regular dictionaries.
Advantages compared to normal dictionary object:
- OrderedDicts are optimized for reordering operations.
- They can be frequently reordered.
- They remember the order of insertion.
- They include methods that help in reordering like popitem() and move_to_end().
Regular dictionaries are better at mapping operations than insertion operations.
Question
OrderedDicts are a collection of:
Declaration of an OrderedDict
Note: For this examples we'll use the Python 3 interpreter interactively.
First we must import OrderedDict from the collections module
>>> from collections import OrderedDict
Now declare and initialize an OrderedDict named MyDict with key: value pairs: a = 5, b = 2 and c = 7.
>>> MyDict = OrderedDict(a=5, b=2, c=7)
OrderedDict's methods
An OrderedDict includes all regular dict methods like list(), len() and others, plus popitem() and move_to_end(). These two methods help the user reorder the OrderedDict as needed.
popitem(last=True)
popitem(last=True)
This method pops an item from the OrderedDict. It returns and removes a value and its key. Items are popped in LIFO order if the True argument is passed, or in FIFO order if the False argument is passed.
Pop the last inserted item like this:
>>> MyDict.popitem(True)
This pops item c.
Pop the first item by passing False as an argument:
>>> MyDict.popitem(False)
This pops item a.
move_to_end
move_to_end(key, last=True)
This method moves items to the end or beginning of the OrderedDict. It receives two arguments, key and last. The key argument, allows the user to select a item to move and last helps the user choose where to move the item. If True is passed as the last argument. If last is False, the item gets moved to the beginning of the OrderedDict.
>>> MyDict.move_to_end('a', True)
This moves the a item to the top of the OrderedDict.
>>> MyDict.move_to_end('a', False)
This moves the a item back to the end of the OrderedDict.
Conclusion
OrderedDicts are dictionaries which allow the user to improve reordering of items within the object. They include special methods which help the user in reordering tasks. OrderedDicts can be used as a base to create new subclasses which take advantage of this properties.
With this article at OpenGenus, you must have a complete idea of OrderedDict in Python. Enjoy.
Sign up for FREE 3 months of Amazon Music. YOU MUST NOT MISS.