简体   繁体   中英

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

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 ?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM