如何以人类可读的方式将python dict序列化为文本?

sds*_*sds 2 python serialization readability human-readable

我有一个python,dict其键和值是字符串,整数和其他dicts和元组(json不支持这些).我想将其保存到文本文件,然后从文件中读取它. 基本上,我想要read内置的对应物print(如在Lisp中).

约束:

  1. 该文件必须是人类可读的(因此pickle已经出来)
  2. 无需检测圆形.

还有比json更好的东西吗?

use*_*471 8

您可以使用repr()dict,然后将其读回,并解析它ast.literal_eval().它与Python本身一样可读.

例:

In [1]: import ast

In [2]: x = {}

In [3]: x['string key'] = 'string value'

In [4]: x[(42, 56)] = {'dict': 'value'}

In [5]: x[13] = ('tuple', 'value')

In [6]: repr(x)
Out[6]: "{(42, 56): {'dict': 'value'}, 'string key': 'string value', 13: ('tuple', 'value')}"

In [7]: with open('/tmp/test.py', 'w') as f: f.write(repr(x))

In [8]: with open('/tmp/test.py', 'r') as f: y = ast.literal_eval(f.read())

In [9]: y
Out[9]:
{13: ('tuple', 'value'),
 'string key': 'string value',
 (42, 56): {'dict': 'value'}}

In [10]: x == y
Out[10]: True
Run Code Online (Sandbox Code Playgroud)

您也可以考虑将pprint模块用于更友好的格式化输出.

  • 值得注意的是,"simplejson"比这更快几个数量级,尽管这比天真的`json`略快 (2认同)
  • @JoranBeasley很高兴知道.我想不出其他许多像JSON一样简单实现并且类似于人类可读的东西. (2认同)