Reputation: 451
a = {Po_list:[121,122],product_list:[343,434],site_list:[2,63]}
type(a) is 'str'
I tried two things
on using ast.literal_eval(a) the output is malformed string
on using json.loads(a) or simplejson.loads(a).. output is still
string
How should I do it .. To get the the output as dictionary
Upvotes: 1
Views: 851
Reputation: 15204
literal_eval
works. You somehow fed it the wrong input..
a = '{"Po_list": [121, 122], "product_list": [343, 434], "site_list": [2, 63]}'
print(type(a)) # prints: <class 'str'>
from ast import literal_eval as leval
res = leval(a)
print(type(res)) # <class 'dict'>
If I missunderstood and the keys are not quoted, you should probably use regex
to fix that; take a look at the answer by @EricDuminil
Upvotes: 1
Reputation: 54293
If your string looks like "{Po_list:[121,122],product_list:[343,434],site_list:[2,63]}"
, you only need to convert the keys to strings by adding quotes around them before evaluating a
:
>>> import re
>>> from ast import literal_eval
>>> a = "{Po_list:[121,122],product_list:[343,434],site_list:[2,63]}"
>>> re.sub('(\w+)(?=:)', '"\g<1>\"', a)
'{"Po_list":[121,122],"product_list":[343,434],"site_list":[2,63]}'
>>> literal_eval(re.sub('(\w+)(?=:)', '"\g<1>\"', a))
{'Po_list': [121, 122], 'product_list': [343, 434], 'site_list': [2, 63]}
Upvotes: 3