Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to deserialize a python printed dictionary?

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.

like image 433
jperelli Avatar asked Oct 29 '25 14:10

jperelli


2 Answers

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'}
like image 165
Ashwini Chaudhary Avatar answered Oct 31 '25 03:10

Ashwini Chaudhary


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'}
like image 26
Blender Avatar answered Oct 31 '25 04:10

Blender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!