Python Practice Question 5: Dict Insertion Order
Python · Test 1 · question 5 of 10
On CPython 3.12, what does this code print? d = {}; d['b'] = 1; d['a'] = 2; d['c'] = 3; del d['a']; d['a'] = 4; d['b'] = 9; print(list(d))
Show answer and explanation
Answer:
Since Python 3.7, the language guarantees that dicts preserve insertion order, and iterating over a dict (which list(d) does) yields keys in that order. Two rules decide the result here:
Deleting a key and inserting it again puts it at the end, because it is a new insertion. So after del d['a']; d['a'] = 4 the order is b, c, a.
Updating the value of an existing key does not move it. d['b'] = 9 leaves b in first place. Final order: ['b', 'c', 'a'].
Option B is the sorted order; dicts do not sort their keys.
Option C assumes that updating a value moves the key to the end, like a "most recently used" structure. That is not what dicts do (collections.OrderedDict.move_to_end() exists for that).
Option D was true of CPython before 3.6, and ordering was only an implementation detail in 3.6. From 3.7 on it is part of the language specification.
Reference: Built-in Types: Mapping Types - dict