3

This StackOverflow answer says python dicts keep insertion order of keys as of python 3.7. The comments to that answer discuss the implementation details of what happens when a key is deleted. I'd like to know: what does the language spec guarantee about key order in the face of deletes (preferably with a link)?

Based on the discussion, I bet it guarantees insertion order of the undeleted elements, but I've been unable to find confirmation.

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
dfrankow
  • 20,191
  • 41
  • 152
  • 214

1 Answers1

3

The language guarantees that undeleted elements will remain in the same order after a key is deleted.

The Python language reference states (emphasis mine):

Dictionaries preserve insertion order, meaning that keys will be produced in the same order they were added sequentially over the dictionary. Replacing an existing key does not change the order, however removing a key and re-inserting it will add it to the end instead of keeping its old place.

The bolded text would not be true if the order of keys changed after a deletion.

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33