How to serialize a python dict to text, in a human-readable way?

独自空忆成欢 提交于 2020-01-04 14:00:45

问题


I have an python dict whose 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 a read counterpart to the built-in print (like in Lisp).

Constraints:

  1. the file must be human readable (thus pickle is out)
  2. no need to detect circularities.

Is there anything better than json?


回答1:


You could use repr() on the dict, then read it back in and parse it with ast.literal_eval(). It's as human readable as Python itself is.

Example:

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

You may also consider using the pprint module for even friendlier formatted output.




回答2:


Honestly, json is your answer [EDIT: so long as the keys are strings, didn't see the part about dicts as keys], and that's why it's taken over in the least 5 years. What legibility issues does json have? There are tons of json indenter, pretty-printer utilities, browser plug-ins [1][2] - use them and it certainly is human-readable. json(/simplejson) is also extremely performant (C implementations), and it scales, and can be processed serially, which cannot be said for the AST approach (why be eccentric and break scalability?).

This also seems to be the consensus from 100% of people answering you here... everyone can't be wrong ;-) XML is dead, good riddance.

  1. How can I pretty-print JSON? and countless others
  2. Browser JSON Plugins


来源:https://stackoverflow.com/questions/28055565/how-to-serialize-a-python-dict-to-text-in-a-human-readable-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!