pprint dictionary on multiple lines

PythonPython 2.7DictionaryPprint

Python Problem Overview


I'm trying to get a pretty print of a dictionary, but I'm having no luck:

>>> import pprint
>>> a = {'first': 123, 'second': 456, 'third': {1:1, 2:2}}
>>> pprint.pprint(a)
{'first': 123, 'second': 456, 'third': {1: 1, 2: 2}}

I wanted the output to be on multiple lines, something like this:

{'first': 123,
 'second': 456,
 'third': {1: 1,
           2: 2}
}

Can pprint do this? If not, then which module does it? I'm using Python 2.7.3.

Python Solutions


Solution 1 - Python

Use width=1 or width=-1:

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

Solution 2 - Python

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 - Python

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

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

Solution 4 - Python

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.)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmulllhausenView Question on Stackoverflow
Solution 1 - PythonWarren WeckesserView Answer on Stackoverflow
Solution 2 - PythonRyan ChouView Answer on Stackoverflow
Solution 3 - PythonUngodlySpoonView Answer on Stackoverflow
Solution 4 - PythonZach ValentaView Answer on Stackoverflow