How To Deserialize A Python Printed Dictionary?
Solution 1:
Use ast.literal_eval()
and for such cases prefer repr()
over str()
, as str()
doesn't guarantee that the string can be converted back to useful object.
In [7]: import ast
In [10]: dic = {u'key-a':u'val-a', "key-b":"val-b"}
In [11]: strs = repr(dic)
In [12]: strs
Out[12]: "{'key-b': 'val-b', u'key-a': u'val-a'}"
In [13]: ast.literal_eval(strs)
Out[13]: {u'key-a': u'val-a', 'key-b': 'val-b'}
Solution 2:
You can use eval()
or ast.literal_eval()
. Most repr()
strings can be evaluated back into the original object:
>>> import ast
>>> ast.literal_eval("{'key-b': 'val-b', u'key-a': u'val-a'}")
{'key-b': 'val-b', u'key-a': u'val-a'}
Solution 3:
ast.literal_eval
could be the way to do it for simple dicts, BUT you should probably rethink your design and NOT save such text in database at first place. e.g.
import collections
d = {'a':1, 'b': collections.defaultdict()}
import ast
print ast.literal_eval(repr(d))
This will not work and throw ValueError('malformed string')
basically you won't be convert back dict if it contains any non basic types.
Better way is to dump dict using pickle or json or something like that e.g.
import collections
d = {'a':1, 'b': collections.defaultdict()}
import json
print json.loads(json.dumps(d))
Summary: serialize using repr
, deserialize using ast.literal_eval
is BAD, serialize using json.dumps
and deserialize using json.loads
is GOOD
Post a Comment for "How To Deserialize A Python Printed Dictionary?"