How to force pprint to print one list/tuple/dict element per line?
Asked Answered
S

2

13

How can I force pprint() to print one list/tuple/dict element per line?

>>> from pprint import pprint
>>> my_var = ['one', 'two', ('red','green'), {'state' : 'Oregon', 'city' : 'Portland'}]
>>> pprint(my_var)
['one', 'two', ('red', 'green'), {'city': 'Portland', 'state': 'Oregon'}]

I would like the output to be something like:

['one',
 'two',
 ('red',
  'green'),
 {'city': 'Portland',
  'state': 'Oregon'}]
Salmi answered 21/3, 2013 at 14:42 Comment(0)
S
11

Use a width=1 argument to pprint():

>>> from pprint import pprint
>>> my_var = ['one', 'two', ('red','green'), {'state' : 'Oregon', 'city' : 'Portland'}]
>>> pprint(my_var, width=1)
['one',
 'two',
 ('red',
  'green'),
 {'city': 'Portland',
  'state': 'Oregon'}]
>>>

"pprint - Data pretty printer" documentation

Salmi answered 21/3, 2013 at 14:42 Comment(3)
This works well for relatively flat objects but does not work out to one per line for deeply nested objects whereas I'd like to achieve a newline after each opening brace. For instance, try pprinting {u'a': {u'b': {u'c': {u'd': {u'foo': 1, u'bar': 2}}}}}.Miniature
@TaylorEdmiston if your dictionary can be json encoded then a quick way to achieve that would be to use: print(json.dumps(mydict, indent=2))Guanabara
Thanks! This got me looking at all the pprint options... I'm generating some python code with very large nested dictionaries, and I wanted to be able to print pretty long lines, but wrap them at a width that wouldn't make my IDE (Eclipse) barf. I used width=4000 and compact=true. Of course, I wish Eclipse's editor could handle long lines...Cobaltite
I
1

I use:

print(json.dumps(mydict, 
         indent=2).replace('true','True').replace('false','False'))

Otherwise, json transforms boolean values to lowercase. Of course, it doesn't work correctly if these keywords are part of some other string! Then regex replacements can be used.

Ivory answered 16/6, 2023 at 18:43 Comment(1)
It works great for list for strings and printing each on a separate line.Gwenn

© 2022 - 2025 — McMap. All rights reserved.