Pretty printing dicts with compact=True

Max Zettlmeißl max at zettlmeissl.de
Tue Sep 11 13:05:30 EDT 2018


On Tue, Sep 11, 2018 at 1:58 PM, Nicolas Hug <niourf at gmail.com> wrote:
> pprint({x: x for x in range(15)}, compact=True)
>
> would be be printed in 15 lines while it could fit on 2.
>
>
> Is this a bug or was this decided on purpose?

It is on purpose as can be seen in the code for pprint [1], which
calls _format [2], which in the case of a dictionary calls
_pprint_dict [3], which ultimately calls _format_dict_items [4].
(which does not use compact or rather _compact)

To me it also seems to be the most sensible behaviour, since
dictionaries with their keys and values are different from most other
sequences. In a dictionary the relation between keys and values is the
most important one and reading a dictionary certainly is easier if
each key value pair has a line of it's own. (Especially if the keys
and values vary a lot in their lengths.)

[1] https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L138
[2] https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L154
[3] https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L180
[4] https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L333



More information about the Python-list mailing list