Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - pprint large dict nicely?

I'm trying to pretty print dictionary which could get quite big and I want to make it as readable as possible. Though it still does not look like how I would manually write it (with new lines and indentation when needed).

I'm trying it to have format like this (2 spaces indentation):

{
  'a': {
         '1': [],
         '2': []
       },
  'b': {
         '1': [],
         '2': [],
       }
}

Now originally dict looks like this (without using pprint):

{'test': {'0.2.0': {'deploy': {'some.host.com': {'outputs': [], 'inputs': []}},
   'release': {'some.git': {'outputs': [], 'inputs': []}}},
  '0.1.0': {'deploy': {'some.host.com': {'outputs': [], 'inputs': []}},
   'release': {'some.git': {'outputs': [], 'inputs': []}}}},
 'stage': {'0.1.0': {'deploy': {'stage.com': {'outputs': [], 'inputs': []}},
   'release': {'stage.git': {'outputs': [], 'inputs': []}}}}}

with: pprint.pprint(my_dict), it looks like:

{'stage': {'0.1.0': {'deploy': {'stage.com': {'inputs': [], 'outputs': []}},
                     'release': {'stage.git': {'inputs': [], 'outputs': []}}}},
 'test': {'0.1.0': {'deploy': {'some.host.com': {'inputs': [], 'outputs': []}},
                    'release': {'some.git': {'inputs': [], 'outputs': []}}},
          '0.2.0': {'deploy': {'some.host.com': {'inputs': [], 'outputs': []}},
                    'release': {'some.git': {'inputs': [], 'outputs': []}}}}}

Well not that different. I tried playing with pprint.pprint options like indent, width, compact, but none seem to format the way I want. Is it possible to achieve similar formatting with pprint as I mentioned above? Or maybe there is some better tool for that?

P.S If you would suggest some other tool, it would be great to be able to write to file with that tool aswel. Cause I'm using pprint to directly write to file.

like image 810
Andrius Avatar asked Aug 28 '26 18:08

Andrius


1 Answers

You can do that with JSON module

import json
_d = {'a': {'1': [],'2': []},'b': {'1': [],'2': [],}}
print json.dumps(_d, indent=2)
like image 85
Priyank Chheda Avatar answered Aug 31 '26 08:08

Priyank Chheda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!