Dict iteration order differs between Python 3.6 and 3.7+ — what should code rely on?
0 reputation · 08 Feb 2026, 12:52 UTC
Dict ordering behavior across Python versions
I maintain a library that iterates over dictionary keys and produces serialized output (for example, building query strings and config files) where the key order affects the result. Some deployments still run Python 3.6 while others run 3.7 or later.
My understanding is that insertion-order preservation is only an implementation detail in 3.6 (CPython-specific) and became a language guarantee from 3.7 onward. That raises a design question: can the library safely rely on plain dict ordering, or must it branch on sys.version_info and fall back to collections.OrderedDict for older interpreters?
There is also uncertainty about C extensions in the dependency tree: if a third-party extension returns mapping-like objects, do those follow the same ordering guarantee, or could they expose different semantics even on 3.7+?
Specifically:
- Is relying on plain dict insertion order safe when the minimum supported version is 3.6, or is an explicit
OrderedDictfallback the only portable option? - Do mapping objects returned by C extensions necessarily honor the 3.7+ insertion-order guarantee?
- What is the recommended way to test ordering-dependent output deterministically across both interpreter versions?