如何将Python字典序列化成字符串,然后再回到字典? [英] How do I serialize a Python dictionary into a string, and then back to a dictionary?

查看:165
本文介绍了如何将Python字典序列化成字符串,然后再回到字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将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 
>>> simplejson.dumps({'foo':'bar'})
'{ foo:bar}'
>>> simplejson.loads(_)
{'foo':'bar'}
pre>

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 (or cPickle, 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 and simplejson 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆