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

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

问题描述

如何将 Python 字典序列化为字符串,然后再返回到字典?字典里面会有列表和其他字典.

解决方案

这取决于你想用它做什么.如果你只是想保存它,你应该使用 pickle(或者,如果您使用的是 CPython 2.x,cPickle,速度更快).

<预><代码>>>>进口泡菜>>>pickle.dumps({'foo': 'bar'})b'x80x03}qx00Xx03x00x00x00fooqx01Xx03x00x00x00barqx02s.'>>>pickle.loads(_){'foo': 'bar'}

如果你想让它可读,你可以使用 json:

<预><代码>>>>导入json>>>json.dumps({'foo': 'bar'})'{"foo": "bar"}'>>>json.loads(_){'foo': 'bar'}

然而,

json 支持的内容非常有限,而 pickle 可用于任意对象(如果它不能自动工作,该类可以定义 __getstate__ 来精确指定它应该如何被腌制).

<预><代码>>>>泡菜.转储(对象())b'x80x03cbuiltins object qx00)x81qx01.'>>>json.dumps(object())回溯(最近一次调用最后一次):...类型错误:<对象对象在 0x7fa0348230c0>不是 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, if you’re using CPython 2.x, cPickle, which is faster).

>>> import pickle
>>> pickle.dumps({'foo': 'bar'})
b'x80x03}qx00Xx03x00x00x00fooqx01Xx03x00x00x00barqx02s.'
>>> pickle.loads(_)
{'foo': 'bar'}

If you want it to be readable, you could use json:

>>> import json
>>> json.dumps({'foo': 'bar'})
'{"foo": "bar"}'
>>> json.loads(_)
{'foo': 'bar'}

json is, however, very limited in what it will support, while pickle can be used for arbitrary objects (if it doesn't work automatically, the class can define __getstate__ to specify precisely how it should be pickled).

>>> pickle.dumps(object())
b'x80x03cbuiltins
object
qx00)x81qx01.'
>>> json.dumps(object())
Traceback (most recent call last):
  ...
TypeError: <object object at 0x7fa0348230c0> is not JSON serializable

这篇关于如何将 Python 字典序列化为字符串,然后再返回到字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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