How to serialize python dict to text, from a human point of view?

I have python dictwhose keys and values ​​are strings, integers and other dicts and tuples ( json does not support those ). I want to save it to a text file and then read it from the file. Basically, I want readto match the built-inprint (for example, in Lisp).

Limitations:

  • the file must be human readable (so pickle is missing)
  • no need to detect circular values.

Is there anything better than json ?

+2
source share
2 answers

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

pprint .

+7

, json - [: , dicts ], 5 . json? json indenter, , [1] [2] - , , , . json (/simplejson) ( C), , AST ( ?).

100% , ... ;-) XML , .

+1

Source: https://habr.com/ru/post/1688161/


All Articles