Python Dict is Ordered in Python 3.7+? – Python Tutorial

By | May 23, 2023

As to python dictionary, is it ordered in python 3.7+? The answer is Yes.

Look at this example:

print("Regular dictionary")
d={}
d['a']='A'
d['b']='B'
d['c']='C'
d['d']='D'
print(d)

Run this code many times, you will see:

Regular dictionary
{'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}

The key order of dictionary d is not changed.

From python manual, we can see:

https://docs.python.org/3.7/library/stdtypes.html#mapping-types-dict

Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.

>>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> list(d)
['one', 'two', 'three', 'four']
>>> list(d.values())
[1, 2, 3, 4]
>>> d["one"] = 42
>>> d
{'one': 42, 'two': 2, 'three': 3, 'four': 4}
>>> del d["two"]
>>> d["two"] = None
>>> d
{'one': 42, 'three': 3, 'four': 4, 'two': None}