sds*_*sds 2 python serialization readability human-readable
我有一个python,dict
其键和值是字符串,整数和其他dicts和元组(json不支持这些).我想将其保存到文本文件,然后从文件中读取它.
基本上,我想要read
内置的对应物print
(如在Lisp中).
约束:
还有比json更好的东西吗?
您可以使用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
模块用于更友好的格式化输出.