Are Dictionaries Ordered in Python?


Dictionaries are ordered

As of Python version 3.7, dictionaries are ordered.

In the previous versions of Python, that is Python 3.6 and earlier, dictionaries are unordered.

Now, what does ordered key-value pairs in a dictionary mean?

It means that the order of keys provided during the creation of a dictionary is preserved.

Consider the following dictionary.

dict1 = {
    "key1": value1,
    "key2": value2,
    "key3": value3,
    "key4": value4}

We have key1 followed by key2 followed by key3 followed by key4. This order of keys is preserved while accessing the key-value pairs of a dictionary.

Suppose we are accessing the key-value pairs in this dictionary using a For loop, then, we would get the key1 first, then key2, then key3, and then key4. Thus the order of given keys is preserved.

If we insert a new key-value "key5":value5, then this would be inserted at the end of the dictionary.

Example

In the following example, we take the above mentioned dictionary, and print the dictionary using print statement. The order of the key-value pairs printed out must be same as that of given in the dictionary. Also, we use a For loop to print out the key-value pairs, the order must be same.

Python Program

dict1 = {
    "key1": 10,
    "key2": 20,
    "key3": 30,
    "key4": 40}

print(dict1)

for key, value in dict1.items():
    print(key, value)

Output

{'key1': 10, 'key2': 20, 'key3': 30, 'key4': 40}
key1 10
key2 20
key3 30
key4 40

Summary

In this tutorial, we learned how dictionaries are ordered in Python, with examples.