Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

OrderedDict in Python

📅 2016-Jun-14 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ ordereddict, python ⬩ 📚 Archive

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

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧