如何将字典保存到文件中,保持良好的格式?

Pin*_*ice 3 python dictionary file save output

如果我有这样的字典:

{
  "cats": {
           "sphinx": 3,
           "british": 2
          },
  "dogs": {}
}
Run Code Online (Sandbox Code Playgroud)

并尝试将其保存到文本文件,我得到这样的东西:

{"cats": {"sphinx": 3}, {"british": 2}, "dogs": {}}
Run Code Online (Sandbox Code Playgroud)

如何以漂亮的格式保存字典,因此人眼很容易阅读?

Ale*_*der 6

您可以导入json并指定缩进级别:

import json

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

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

请注意,这是一个字符串,但是:

>>> j
'{\n    "cats": {\n        "sphinx": 3, \n        "british": 2\n    }, \n    "dogs": {}\n}'
Run Code Online (Sandbox Code Playgroud)


Vad*_*der 4

您可以使用pprint来实现:

import pprint
pprint.pformat(thedict)
Run Code Online (Sandbox Code Playgroud)

  • @zondo我用过这个:file.write(pprint.pformat(my_dict)) (5认同)