Home > Blockchain >  How to convert a string dictionary to dictionary in python?
How to convert a string dictionary to dictionary in python?

Time:08-26

I have dictionary in form of string -

dict_in_str = '{"name":"wrong_answers","y":8,"color": colorForSections["wrong_answers"]}'

I have tried both, the json.loads(dict_in_str) and ast.literal_eval(dict_in_str) methods.

But both of them are giving

json.decoder.JSONDecodeError: Expecting value: line 1 column 40 (char 39)

and

ValueError: malformed node or string: <_ast.Subscript object at 0x02082B20>

respectively. On forums and tutorials I have looked upon these methods seems to work.

CodePudding user response:

you can replace and split into list and then convert into dict.

dict_in_str = '{"name":"wrong_answers","y":8,"color": 
colorForSections["wrong_answers"]}'
data_lst = dict_in_str.replace("'", '').replace('"', '').replace('{', 
'').replace('}', '').replace(':', ',').split(',')
lst = [i.strip() for i in data_lst if i.strip()]
result = {lst[i]: lst[i   1] for i in range(0, len(lst), 2)}
print(result)
print(type(result))

>>> {'name': 'wrong_answers', 'y': '8', 'color': 'colorForSections[wrong_answers]'}

<class 'dict'>

CodePudding user response:

As mentioned by deceze and matszwejca, he issue is your value in your last part, "color": colorForSections["wrong_answers"]. It can't evaluate the value of 'colorForSections["wrong_answers"]' because it's in a string. When you run loads() on it, it can't convert it to any known type (I'm assuming that's what's going on, egg on my face if not). Try passing in the key string ("wrong_answers") and then retrieving the value from colorForSections after you run loads() on the string. Something like:

dict_in_str = '{"name":"wrong_answers","y":8,"color": "wrong_answers"}'
x = json.loads(dict_in_str)
color = colorForSections[x['color']]
  • Related