Tarun Khaneja
Tarun Khaneja

Reputation: 451

how to convert string to dictionary using python (malformed string)

a = {Po_list:[121,122],product_list:[343,434],site_list:[2,63]}

type(a) is 'str'

I tried two things

  1. on using ast.literal_eval(a) the output is malformed string

  2. 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

Answers (2)

Ma0
Ma0

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

Eric Duminil
Eric Duminil

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

Related Questions