mulllhausen mulllhausen - 2 months ago 21
Python Question

python pprint dictionary on multiple lines

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

Answer

Use width=1 or width=-1:

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