Pretty printing Python dictionary/lists in "Black style"

1.8k Views Asked by At

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.

0

There are 0 best solutions below