Python Dictionary Insertion Order
Core idea
Dictionaries preserve the order in which keys are inserted, a language guarantee since Python 3.7. Replacing an existing value leaves its key in the same position. Removing a key and inserting it again puts it at the end. This is not alphabetical sorting.
tasks = {"wash": 1, "dry": 2}tasks["fold"] = 3print(list(tasks))The new key appears last.
Replace then reinsert
tasks = {"wash": 1, "dry": 2}tasks["wash"] = 4print(list(tasks))del tasks["wash"]tasks["wash"] = 4print(list(tasks))Replacement preserves position; reinsertion changes it.
Compare different orders
a = {"x": 1, "y": 2}b = {"y": 2, "x": 1}print(a == b)print(list(a) == list(b))Dictionary equality compares entries, not insertion order.
Common mistake
An integer key is still a key, not a position. To read the first inserted key in a small dictionary, use list(d)[0] only when it is nonempty.
Practice
Insert three route labels, replace the middle value, then delete and reinsert its key. Predict the key list each time.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Insertion order
Check your understanding of dictionary order.
What is printed?
print(list({"z": 1, "a": 2}))What is printed?
d = {"x": 1, "y": 2}d["x"] = 5print(list(d))What is printed?
d = {"x": 1, "y": 2}del d["x"]d["x"] = 1print(list(d))Does insertion order affect dictionary equality?