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.

Answers


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

Need Your Help

First time SQL Server setup

sql sql-server

This will be my first time setting up an SQL Server, so really I'm just after advice from people who have done such a thing before. The Do's and Do not's basically.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.