How to pretty print nested dictionaries?

My first thought was that the JSON serializer is probably pretty good at nested dictionaries, so I’d cheat and use that:

>>> import json
>>> print(json.dumps({'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}},
...                  sort_keys=True, indent=4))
{
    "a": 2,
    "b": {
        "x": 3,
        "y": {
            "t1": 4,
            "t2": 5
        }
    }
}

Leave a Comment