OrderedDict in Python

Lists and dictionaries are the fundamental data structures in Python. One of the problems I regularly face with dictionary is that I cannot iterate the keys in a certain order. In many problems, I have the keys in a certain order, I am able to insert the keys in that order, but need to be able to later iterate them in that same order.

The solution to these exact problems is the OrderedDict. It is just like the dictionary, but maintains the order of insertion of the keys. Later when you iterate over its keys, the order is the same as you inserted them in. I am guessing it is implemented by maintaining the keys in a list alongside a dictionary.

Usage of the OrderedDict is same as dictionary in all ways. The only difference is in creating it:

import collections

d = collections.OrderedDict()

Tried with: Python 3.4

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.