Hone

Lessons · Python · dicts keep order

Dicts remember insertion order

Since Python 3.7 a dict keeps keys in the order they were added. It is not sorted; it is remembered.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Column order in a CSV export, the order fields appear in JSON, 'first seen' logic: all rely on insertion order, and all break if you assume alphabetical.

How to think about it

Want the order you inserted? You already have it. Want alphabetical or by value? sorted(d) or sorted(d.items(), key=...). Never assume a dict is sorted.

Worked example

d = {"b": 2, "a": 1}
b was added first.
print(list(d))
['b', 'a']: insertion order, not alphabetical.
d["c"] = 3
A new key.
print(list(d))
['b', 'a', 'c']: new keys go at the end.
print(sorted(d))
['a', 'b', 'c']: sorted when you ask for it.

Your turn

Column names in the order they were added.

cols = (row)

The trap

Deleting a key and re-adding it moves it to the end. Updating the value of an existing key does not move it.

Practise dicts keep order on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.