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

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

如果我有这样的字典:

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

并尝试将其保存到文本文件中,我得到这样的结果:

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

如何将字典保存为漂亮的格式,以便人眼易于阅读?

你可以使用 pprint

import pprint
pprint.pformat(thedict)

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

import json

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

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

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

>>> j
'{\n    "cats": {\n        "sphinx": 3, \n        "british": 2\n    }, \n    "dogs": {}\n}'

如果你想保存成更标准的格式,你也可以使用,例如yaml文件(以及相关的python包http://pyyaml.org/wiki/PyYAMLDocumentation),代码如下喜欢:

import yaml
dictionary = {"cats": {"sphinx": 3}, {"british": 2}, "dogs": {}}
with open('dictionary_file.yml', 'w') as yaml_file:
     yaml.dump(dictionary, stream=yaml_file, default_flow_style=False)

dump 创建一个要写入文件的 yaml 格式的字符串。请注意,可以指定流并将内容立即写入文件。如果在写入文件之前由于某种原因需要获取字符串,则不指定它并在对文件使用 write 函数后写入。 另请注意,参数 default_flow_style 允许使用更好的格式;在示例中,文件看起来是:

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

再次加载字典中的 yaml 文件:

import yaml
with open('dictionary_file.yml', 'r') as yaml_file:
    dictionary = yaml.load(yaml_file)

您可以使用 Python Object Notation 模块转储它(pon:免责声明我是该模块的作者)

from pon import PON, loads

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

pon = PON(obj=data)
pon.dump()

给出:

dict(
    cats=dict(
        sphinx=3,
        british=2,
    ),
    dogs=dict(    ),
)

这又是正确的 Python,但是使用 dict 交换键所需的引号字符串。

您可以通过以下方式再次加载:

read_back = loads(open('file_name.pon').read())
print(read_back)

给予:

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

请注意 loads() 不会 评估字符串,它实际上使用 python 的内置解析器安全地解析它。

PON 还允许您从文件中加载 python 词典,这些词典具有注释条目,并在保留注释的同时转储它们。这就是它真正有用的地方。


或者,如果您想要像 YAML 格式那样任意更具可读性的东西,您可以使用 ruamel.yaml 并执行:

import ruamel.yaml
ruamel.yaml.round_trip_dump(data, stream=open('file_name.yaml', 'wb'), indent=4) 

这会为您提供一个文件 file_name.yaml,其内容为:

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

它使用您似乎更喜欢的缩进(并且比@alberto 的版本更有效)