Skip to content

Ordering of dict keys when using msgspec.json.encode #825

Description

@sbalian

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?

Activity

  1. jcrist commented on Mar 17, 2025

    @jcrist
    Member

    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.

  2. sbalian commented on Mar 17, 2025

    @sbalian
    Author

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

  3. added a commit that references this issue on Apr 10, 2026
    20c0282
  4. Siyet commented on Apr 10, 2026

    @Siyet
    Contributor

    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:

    a = {"b": 1, "a": 2}
    b = {"a": 2, "b": 1}
    assert a == b  # True

    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.

    Opened #1011 to fix the wording.

  5. added a commit that references this issue on Apr 10, 2026
    20cc59d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions