DEV Community

Cover image for Python's Collections Module: OrderdDict
Kathan Vakharia
Kathan Vakharia

Posted on

Python's Collections Module: OrderdDict

Why do we need OrderedDict anway?

Since dictionaries in python maintain their insertion order completely after python 3.7+, use case of OrderedDict is fading away slowly. But still there are some helper methods and functions that we can leverage while using OrderedDicts.

image

Creating OrderedDict

Since, it is a dict sub-class. It can leverage all the functionalities of dictionary.
imageLet's discuss some important methods pertaining to OrderedDict only.

popitem method

The popitem(last = True) method for ordered dictionaries returns and removes a (key, value) pair.

The pairs are returned in ,

  1. LastInFirstOut(LIFO) order if last is true. That is to say, last pair is popped.(default)
  2. FirstInFirstOut(FIFO) order if false. That is to say, first pair is popped.
from collections import OrderedDict

ord_dict = OrderedDict({"fname": "The",
                        "lname": "CodeBlooded",
                        "founder": "A Geek",
                        "Ran by": "Geeks"})

last_pair = ord_dict.popitem()  # last=True by default
first_pair = ord_dict.popitem(last=False)

print(f'last pair: {last_pair}')
print(f'first pair: {first_pair}')

"""OUTPUT 
last pair: ('Ran by', 'Geeks')
first pair: ('fname', 'The')
"""
Enter fullscreen mode Exit fullscreen mode

move_to_end method

The move_to_end(key, last=True) moves an existing key to either end of an ordered dictionary.

The item is moved to the right end if last is true (default) or to the beginning if last is false.

from collections import OrderedDict

ord_dict = OrderedDict({"fname": "The",
                        "lname": "CodeBlooded",
                        "founder": "A Geek",
                        "Ran by": "Geeks"})

print(f'Before =>\n{ord_dict}')
# move to right-most end
ord_dict.move_to_end('founder')

# move to left-most end
ord_dict.move_to_end('Ran by', last=False)

print(f'After =>\n{ord_dict}')

"""OUTPUT 
Before =>
OrderedDict([('fname', 'The'), ('lname', 'CodeBlooded'), 
            ('founder', 'A Geek'), ('Ran by', 'Geeks')])
After =>
OrderedDict([('Ran by', 'Geeks'), ('fname', 'The'), 
            ('lname', 'CodeBlooded'), ('founder', 'A Geek')])

"""
Enter fullscreen mode Exit fullscreen mode

💡 KeyError is raised if given key is not present in the dictionary.

And that wraps our discussion on OrderedDict! If you notice all of Collections classes we discussed till now are dict subclass, isn't it interesting ? It's testament to how much powerful dictionaries in python are 😎

Top comments (0)