TIMEX TIMEX - 4 months ago 19
Python Question

How do I serialize a Python dictionary into a string, and then back to a dictionary?

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.

Answer

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