You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Ordering of dict keys when using msgspec.json.encode #825
When using msgspec.json.encode for a dictionary in Python 3.12, for example:
msgspec.json.encode({"b": 1, "a": 2})
I see that the ordering of the keys is preserved (with the default order=None). The above example returns b'{"b":1,"a":2}'. Is this order guaranteed to be the same between runs?
If order=None the default iteration order of the collection is used. In the case of dicts this is insertion order. As long as the insertion order is the same between runs, then yes this is guaranteed to be consistent.
Thanks! FYI what made be doubt this is the docstring : "Unordered collections (sets, dicts) are sorted to ensure a consistent output between runs" for order='deterministic'.
Reopening this thread - you're right that the docstring is misleading. Dicts in Python 3.7+ are ordered by insertion (per the language spec), so calling them "unordered collections" is technically incorrect.
The actual reason order='deterministic' sorts dict keys is not "consistency between runs" (insertion order is already stable within a run), but to ensure that two dicts which compare equal produce identical encoded output, regardless of how they were constructed. For example:
Without sorting, these would encode to different bytes in deterministic mode, defeating the purpose for use cases like content-addressed storage, cache keys, or hashing.
Activity
jcrist commentedon Mar 17, 2025
If
order=Nonethe default iteration order of the collection is used. In the case of dicts this is insertion order. As long as the insertion order is the same between runs, then yes this is guaranteed to be consistent.sbalian commentedon Mar 17, 2025
Thanks! FYI what made be doubt this is the docstring : "Unordered collections (sets, dicts) are sorted to ensure a consistent output between runs" for
order='deterministic'.Clarify wording of order='deterministic' in encoder docstrings
Siyet commentedon Apr 10, 2026
Reopening this thread - you're right that the docstring is misleading. Dicts in Python 3.7+ are ordered by insertion (per the language spec), so calling them "unordered collections" is technically incorrect.
The actual reason
order='deterministic'sorts dict keys is not "consistency between runs" (insertion order is already stable within a run), but to ensure that two dicts which compare equal produce identical encoded output, regardless of how they were constructed. For example:Without sorting, these would encode to different bytes in
deterministicmode, defeating the purpose for use cases like content-addressed storage, cache keys, or hashing.Opened #1011 to fix the wording.
Clarify wording of order='deterministic' in encoder docstrings (#1011)