Dictionary Insertion Order and Sorting

Python dictionaries preserve insertion order. This order is useful for source history and can differ from ascending key order.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace updates and reinsertions
  2. Choose final report order
  3. Trace updates, removals and reinsertions
  4. Use a sort key whenever input order can vary

Trace updates and reinsertions

Insert keys b, a, and c in that order. Iteration yields b, a, c. Updating b's stored value keeps that position. Deleting b and inserting it again places b after c. Ordering a sequence of events describes why these histories are distinct.

Choose final report order

For alphabetic output, sort the explicit keys. For first-seen output, preserve insertion while building the dictionary. Use a tie or ordering test containing distinct labels whose arrival and alphabetical order disagree.[1]

Trace updates, removals and reinsertions

Insert keys S, N and E in that order into a Python dictionary. Updating N's value leaves its position in the iteration order. Deleting N and inserting it again puts it after E. A report relying on first sighting can use insertion order if its construction process is controlled. A report ordered by key needs a separate sorting step. See stable ordering in practice.

Use a sort key whenever input order can vary

Two files can contain the same key-value pairs in different orders and produce dictionary values that compare equal. Serializing them in insertion order can still produce different output. For deterministic report rows, sort by the intended output fields, with an explicit tie rule. Keep numeric sorting distinct from sorting textual numbers. Test equivalent dictionaries built in opposite order. See converting maps to rows.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩