Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pprint does not keep the order of dict keys #115985

Closed
mattermat opened this issue Feb 27, 2024 · 4 comments
Closed

pprint does not keep the order of dict keys #115985

mattermat opened this issue Feb 27, 2024 · 4 comments
Labels
type-bug An unexpected behavior, bug, or error

Comments

@mattermat
Copy link

mattermat commented Feb 27, 2024

Bug report

Bug description:

As in the title:

from pprint import pprint

a = {
    "a": [1, 2, 3],
    "b": [1, 2, 3],
    "c": [1, 2, 3],
}

b = {
    "b": [1, 2, 3],
    "c": [1, 2, 3],
    "a": [1, 2, 3],
}

pprint(a)
pprint(b)

gives the following:

{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}

CPython versions tested on:

3.12

Operating systems tested on:

Windows

@mattermat mattermat added the type-bug An unexpected behavior, bug, or error label Feb 27, 2024
@kotnen
Copy link

kotnen commented Feb 27, 2024

This is the expected behaviour, and is not a bug.

From the documentation,

If sort_dicts is true (the default), dictionaries will be formatted with their keys sorted, otherwise they will display in insertion order.

As a side note, it's always good to check the documentation to see what the expected behaviour is before reporting something as a bug. (Please don't take that as a criticism of this bug report though; it's appreciated that you took the time out of your day to help out the Python project.)

@AlexWaygood
Copy link
Member

Thanks for the report! As @kotnen says, this is longstanding and intentional behaviour that we wouldn't be able to easily change without breaking backwards compatibility. However, I think there's a number of documentation improvements we could make here to call out the default behaviour of pprint.pprint() so that users are more aware of it. I've opened #115986 to track that.

@AlexWaygood AlexWaygood closed this as not planned Won't fix, can't repro, duplicate, stale Feb 27, 2024
@mattermat
Copy link
Author

Hi @kotnen ,

I should have checked the documentation before opening the issue...
Given that dict keeps the order of the keys I didn't expect pprint not doing the same.

Thanks for you feedback!

@terryjreedy
Copy link
Member

pprint predate ordered keys by at least a decade. Sorting keys was then part of the expectation of 'pretty'. It also enabled a predictable output string for doctests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type-bug An unexpected behavior, bug, or error
Projects
None yet
Development

No branches or pull requests

4 participants