msgspec icon indicating copy to clipboard operation
msgspec copied to clipboard

Ordering of dict keys when using `msgspec.json.encode`

Open sbalian opened this issue 8 months ago • 2 comments

Question

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?

sbalian avatar Mar 17 '25 18:03 sbalian

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.

jcrist avatar Mar 17 '25 19:03 jcrist

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'.

sbalian avatar Mar 17 '25 19:03 sbalian