How to Maintain Insertion Order in a Dictionary in Python

In Python programming, a dictionary is often an essential data structure since it enables immense manipulations and implementations.

However, maintaining the insertion order in a dictionary can be a bit of a challenge. In this tutorial, we will walk you through the process of achieving this. Thankfully, since Python version 3.7, dictionaries have been ordered.

In Python 3.7 and later, dictionaries keep their insertion order by default, meaning that the order in which the keys are inserted in the dictionary is the same order in which they can be iterated over.

Step 1: Create a dictionary in Python

Firstly, let’s start with creating a dictionary. The dictionary in Python is defined by enclosing a comma-separated list of key-value pairs in curly braces {}. The keys are followed by a colon and then their corresponding values.

Step 2: Add new elements to the dictionary

Let’s add some more elements in the dictionary, and then iterate over the keys.

Step 3: Verify the order of the elements

As we iterate over the keys, we will realize, that the keys are ordered in the same order as they are inserted. The output would be:

Lion
Elephant
Tiger
Zebra
Bison

Full Code

If you’re using an older version of Python (pre 3.7), dictionaries do not maintain order and you may want to use OrderedDict from the collections module which is specifically designed to maintain the order of the elements.

Conclusion

Preserving the insertion order in a dictionary can be very beneficial in many coding scenarios. Fortunately, Python 3.7+, makes it easy to maintain the insertion order in dictionaries as they are ordered by default in these versions.

If you’re working with a version that doesn’t inherently support order preservation, you can always make use of the OrderedDict from the collections module.