如何将Python字典序列化成字符串,然后再回到字典? [英] How do I serialize a Python dictionary into a string, and then back to a dictionary?
问题描述
如何将Python字典序列化成字符串,然后返回到字典?该字典将包含其中的列表和其他字典。
这取决于您想要使用它。如果您只是想保存它,您应该使用 pickle
(或 cPickle
,如果您使用CPython,速度更快)。
>> ;>导入cPickle
>>> cPickle.dumps({'foo':'bar'})
(dp1\\\
S'foo'\\\
p2\\\
S'bar'\\\
p3\\\
s
> >> cPickle.loads(_)
{'foo':'bar'}
但是,如果您希望它可读,您可以使用 json
>>> import json
>> > json.dumps({'foo':'bar'})
'{foo:bar}'
>>> json.loads(_)
{u'foo':u'bar'}
或 simplejson
。
>>> import simplejson
pre>
>>> simplejson.dumps({'foo':'bar'})
'{ foo:bar}'
>>> simplejson.loads(_)
{'foo':'bar'}
json
和simplejson
他们会l支持cPickle
可以用于对象(如果它不能自动工作,该类可以定义__ getstate __
请详细说明应该如何腌制)。>>> cPickle.dumps(object())
'ccopy_reg\\\
_reconstructor\\\
p1\\\
(c__builtin__\\\
object\\\
p2\\\
g2\\\
NrRp3\\\
。'
>> > json.dumps(object())
追溯(最近的最后一次调用):
...
TypeError:< 0x7fa0348230c0的对象对象不是JSON序列化
>>>>>>>>>>>>>不是JSON可序列化
How do I serialize a Python dictionary into a string, and then back to a dictionary? The dictionary will have lists and other dictionaries inside it.
解决方案It depends on what you're wanting to use it for. If you're just trying to save it, you should use
pickle
(orcPickle
, which is faster, if using CPython as you probably are).>>> import cPickle >>> cPickle.dumps({'foo': 'bar'}) "(dp1\nS'foo'\np2\nS'bar'\np3\ns." >>> cPickle.loads(_) {'foo': 'bar'}
However, if you want it to be readable, you could use
json
>>> import json >>> json.dumps({'foo': 'bar'}) '{"foo": "bar"}' >>> json.loads(_) {u'foo': u'bar'}
or
simplejson
.>>> import simplejson >>> simplejson.dumps({'foo': 'bar'}) '{"foo": "bar"}' >>> simplejson.loads(_) {'foo': 'bar'}
json
andsimplejson
are very limited in what they will support.cPickle
can be used for objects (if it doesn't work automatically, the class can define__getstate__
to specify precisely how it should be pickled).>>> cPickle.dumps(object()) 'ccopy_reg\n_reconstructor\np1\n(c__builtin__\nobject\np2\ng2\nNtRp3\n.' >>> json.dumps(object()) Traceback (most recent call last): ... TypeError: <object object at 0x7fa0348230c0> is not JSON serializable >>> simplejson.dumps(object()) Traceback (most recent call last): ... TypeError: <object object at 0x7fa034823090> is not JSON serializable
这篇关于如何将Python字典序列化成字符串,然后再回到字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!