Search code examples
pythonjsonprintingconsolepprint

Inconsistent printing of nested dict using pprint in Python


I used pprint to pretty print a large nested dict:

import pprint
import json


with open('config.json', 'r') as fp:
    conf = fp.read()


pprint.pprint(json.loads(conf))



{u'cust1': {u'videotron': {u'temperature': u'3000K',
                           u'image_file': u'bloup.raw',
                           u'light_intensity': u'20',
                           u'size': [1920, 1080],
                           u'patches': [[94, 19, 247, 77],
                                        [227, 77, 293, 232],
                                        [77, 217, 230, 279],
                                        [30, 66, 93, 211]]}},
 u'cust2': {u'Rogers': {u'accuracy': True,
                        u'bleed': True,
                        u'patches': [[192,
                                      126,
                                      10,
                                      80],
                                     [318,
                                      126,
                                      10,
                                      80], ...

The 2nd level list cust2.Rogers.patches is unfold whereas cust1.videotron.patches is not. I'd like both not to be unfold, i.e. printed on the same line. Does anyone know how?


Solution

  • You can play with two parameters: width and compact (the last one may be not available for Python 2).

    width -- limits horizontal space.

    And here is description for compact:

    If compact is false (the default) each item of a long sequence will be formatted on a separate line. If compact is true, as many items as will fit within the width will be formatted on each output line.

    But as I understand you can't tell pprint anything about the structure of data and how you want specific elements to be printed.