Skip to content

The pprint module employs a key-value sorting when representing dict obj. #137448

@Stranger-Jie

Description

@Stranger-Jie

Feature or enhancement

Proposal:

The pprint module in Python currently provides a sort_dicts parameter (defaulting to True) to control whether the keys of dict are sorted during output. This sorting method is based solely on the keys of the dict, disregarding the importance of the values. However, in certain scenarios, the keys of a dictionary are merely labels, and users are more concerned with the values associated with these labels. These values might often be class objects that have overridden comparison methods. The current implementation does not meet the need for sorting by values or custom sorting based on values. The use of the value sorting feature for dict in pprint not only retains the efficiency and aesthetics of pprint's output but also avoids potential errors that might be introduced when users manually implement sorting.

from pprint import pprint


class FinalExamResults:
    def __init__(self, score: float, name: str = "") -> None:
        self.score = score  # example

    def __lt__(self, other):
        return self.score < other.score

    def __repr__(self):
        return f"{self.score}"


classmates = {
    "Alice": FinalExamResults(4.0),
    "Bob": FinalExamResults(3.5),
    "Charlie": FinalExamResults(4.4),
    "David": FinalExamResults(3.2),
}


pprint(classmates)
# {'Alice': 4.0, 'Bob': 3.5, 'Charlie': 4.4, 'David': 3.2}

pprint(classmates, sort_dicts_by_key=False)
# {'Charlie': 4.4, 'Alice': 4.0, 'Bob': 3.5, 'David': 3.2}

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

pprint does not keep the order of dict keys #115985
Bug: pprint module print dict object in wrong key sequence #98232

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions