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


how serialize python dictionary string, , dictionary? dictionary have lists , other dictionaries inside it.

it depends on you're wanting use for. if you're trying save it, should use pickle (or cpickle, faster, if using cpython are).

>>> import cpickle >>> cpickle.dumps({'foo': 'bar'}) "(dp1\ns'foo'\np2\ns'bar'\np3\ns." >>> cpickle.loads(_) {'foo': 'bar'} 

however, if want readable, 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 , simplejson limited in support. cpickle can used objects (if doesn't work automatically, class can define __getstate__ specify precisely how should 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 @ 0x7fa0348230c0> not json serializable >>> simplejson.dumps(object()) traceback (most recent call last):   ... typeerror: <object object @ 0x7fa034823090> not json serializable 

Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -