Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a dictionary into a file, keeping nice format?

If I have dictionary like:

{
  "cats": {
           "sphinx": 3,
           "british": 2
          },
  "dogs": {}
}

And try to save it to a text file, I get something like this:

{"cats": {"sphinx": 3}, {"british": 2}, "dogs": {}}

How can I save a dictionary in pretty format, so it will be easy to read by human eye?

like image 521
PinkiNice Avatar asked Mar 19 '16 00:03

PinkiNice


2 Answers

You can import json and specify an indent level:

import json

d = {
  "cats": {
           "sphinx": 3,
           "british": 2
          },
  "dogs": {}
}

j = json.dumps(d, indent=4)
print(j)
{
    "cats": {
        "sphinx": 3, 
        "british": 2
    }, 
    "dogs": {}
}

Note that this is a string, however:

>>> j
'{\n    "cats": {\n        "sphinx": 3, \n        "british": 2\n    }, \n    "dogs": {}\n}'
like image 79
Alexander Avatar answered Sep 20 '22 04:09

Alexander


You can use pprint for that:

import pprint
pprint.pformat(thedict)
like image 24
Vader Avatar answered Sep 21 '22 04:09

Vader