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?
>>> 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.
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'}
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With