OrderedDict in Python Collection

Ordered dictionaries emulate regular dictionaries with a couple of distinctions. The most obvious one you can probably figure out due to the name of the collection, OrderedDicts retains the order in which the items are inserted. Therefore, when you iterate over an OrderedDict the items are returned in the order in which they’re inserted. Also, like builtin dictionaries, OrderedDict has a popitem() method, but the difference is that you can specify where you want to pop from.

For example, you can pop the last item or you can pop the first item; you do this by changing the keyword argument. Also, unlike builtin dictionaries OrderedDicts have a move_to_key() method which specifies the side in which you want to move a key to; you can only move to either end with the default position being at the end. The below code snippets shows how the popitem() and move_to_key() methods work respectively.

>>> from collections import OrderedDict
>>> fruits = OrderedDict({'g': 'grapefruit', 'c': 'citron', 'l': 'lemon'})
>>> fruits.popitem(last='true') # returns pairs in LIFO
('l', 'lemon')
>>> fruits.popitem(last='false') # returns pairs in FIFO
('c', 'citron')

The following code snippet shows how to use the move_to_end() method.

>>> from collections import OrderedDict
>>> nums = OrderedDict({'1': 10, '2': 20, '3': 30, '4': 40, '5': 50})
>>> nums.move_to_end('1', last=True)
>>> nums
OrderedDict([('2', 20), ('3', 30), ('4', 40), ('5', 50), ('1', 10)])
>>> nums.move_to_end('4', last=False)
>>> nums
OrderedDict([('4', 40), ('2', 20), ('3', 30), ('5', 50), ('1', 10)])

Also, OrderedDict supports reverse iteration via the reversed() function. The following code snippet reverses the following OrderedDict:

OrderedDict([('4', 40), ('2', 20), ('3', 30), ('5', 50), ('1', 10)])
>>> for key, value in reversed(nums.items()):
...     print(key, value)

1 10
5 50
3 30
2 20
4 40

>>> nums
OrderedDict([('4', 40), ('2', 20), ('3', 30), ('5', 50), ('1', 10)])

Regular dictionary vs unsorted dictionary

To get a better picture of how OrderedDicts work, lets take a look at regular dictionaries versus the OrderedDicts.

>>> states = ({'ca':'california', 'de': 'delaware', 'az': 'arizona', 'in': 'indiana'})

If we want to sort a normal dictionary we could consider passing the dictionary into the sorted function as indicated below:

>>> sorted(states)
['az', 'ca', 'de', 'in']

The problem is that we don’t get a key/value pair, we only get the key returned. If order is important then instead of using the builtin dictionary we can instead use OrderedDict. Below is one solution on how you can sort an OrderedDict:

>>> from collections import OrderedDict
>>> OrderedDict(sorted(states.items(), key=lambda x: x[0]))
OrderedDict([('az', 'arizona'), ('ca', 'california'), ('de', 'delaware'), ('in', 'indiana')])

The above code snippet sorts the dictionary by key, if you want to sort it by values use the following instead:

>>> OrderedDict(sorted(states.items(), key=lambda x: x[1]))
OrderedDict([('az', 'arizona'), ('ca', 'california'), ('de', 'delaware'), ('in', 'indiana')])

To learn more about the OrderedDict class in python read about them in the collections section of the python docs.

============================================================================ Want to learn how to use Python's most popular IDE Pycharm? In the free pdf guide "Getting the Hang of PyCharm" you'll learn all of the amazing features in PyCharm along with how to get started with data science. Subscribe to the Purcell Consult newsletter and get started A.S.A.P.