1

I don't really fancy the way Python's pprint formats the output. E.g.

import pprint
from datetime import datetime
d = {
    'a': [
        {
            '123': datetime(2021, 11, 15, 0, 0),
            '456': 'cillum dolore eu fugiat nulla pariatur. Excepteur sint...',
            '567': [
                1, 2, 'cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
            ]
        }
    ],
    'b': {
        'x': 'yz'
    }
}
pprint.pprint(d)

Will print:

{'a': [{'123': datetime.datetime(2021, 11, 15, 0, 0),
        '456': 'cillum dolore eu fugiat nulla pariatur. Excepteur sint...',
        '567': [1,
                2,
                'cupidatat non proident, sunt in culpa qui officia deserunt '
                'mollit anim id est laborum.']}],
 'b': {'x': 'yz'}}

But I'd like it to be:

{
    "a": [
        {
            "123": datetime.datetime(2021, 11, 15, 0, 0),
            "456": "cillum dolore eu fugiat nulla pariatur. Excepteur sint...",
            "567": [
                1,
                2,
                "cupidatat non proident, sunt in culpa qui officia deserunt "
                "mollit anim id est laborum.",
            ],
        }
    ],
    "b": {"x": "yz"},
}

I.e. in the style of Black

Is there a parameter of pprint or some 3rd party library to do this? I guess I could use Black for some outputs but I wonder if there is an out-of-the-box solution

Edit: A good suggestion was to use print(json.dumps(d, indent=4)). This does the job if the whole thing is JSON-serializable but unfortunately does not work otherwise.

Ferrard
  • 2,260
  • 3
  • 22
  • 26
  • I wonder if you would be happier with something like `print(json.dumps(d, indent=4))` – Mark Nov 12 '21 at 16:17
  • @Mark good point, the problem is with dicts containing non-JSON-serializable items. Otherwise it does the job. Let me update the question! – Ferrard Nov 15 '21 at 11:28
  • 1
    @Ferrard you can pass a callable as a `default` parameter: `print(json.dumps(d, indent=2, default=lambda o: str(o)))` – rv.kvetch Nov 15 '21 at 16:17
  • If you want the same output as above except wrapped in a string, you could use `repr(o)` in the callable instead. – rv.kvetch Nov 15 '21 at 16:19
  • Thanks both, I think that actually works! – Ferrard Nov 16 '21 at 17:01

0 Answers0