pythonlistdictionarypretty-printpprint

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


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'}]

Solution

  • 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