pprint dictionary on multiple lines

Solution 1:

Use width=1 or width=-1:

In [33]: pprint.pprint(a, width=1)
{'first': 123,
 'second': 456,
 'third': {1: 1,
           2: 2}}

Solution 2:

You could convert the dict to json through json.dumps(d, indent=4)

import json

print(json.dumps(item, indent=4))
{
    "second": 456,
    "third": {
        "1": 1,
        "2": 2
    },
    "first": 123
}

Solution 3:

If you are trying to pretty print the environment variables, use:

pprint.pprint(dict(os.environ), width=1)

Solution 4:

Two things to add on top of Ryan Chou's already very helpful answer:

  • pass the sort_keys argument for an easier visual grok on your dict, esp. if you're working with pre-3.6 Python (in which dictionaries are unordered)
print(json.dumps(item, indent=4, sort_keys=True))
"""
{
    "first": 123,
    "second": 456,
    "third": {
        "1": 1,
        "2": 2
    }
}
"""
  • dumps() will only work if the dictionary keys are primitives (strings, int, etc.)