问题
I have python's str dictionary representations in a database as varchars, and I want to retrieve the original python dictionaries
How to have a dictionary again, based in the str representation of a dictionay?
Example
>>> dic = {u'key-a':u'val-a', "key-b":"val-b"}
>>> dicstr = str(dic)
>>> dicstr
"{'key-b': 'val-b', u'key-a': u'val-a'}"
In the example would be turning dicstr back into a usable python dictionary.
回答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'}
回答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'}
回答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
来源:https://stackoverflow.com/questions/13165479/how-to-deserialize-a-python-printed-dictionary