Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String with backslashes to dictionary

I have the following string:

txt = "{\'legs_a\': 1,\'legs_b\': 0,\'score_a\': 304,\'score_b\': 334,\'turn\': B,\'i\': 2,\'z\': 19}"

When I print it, I see the below output in my console

{'legs_a': 1,'legs_b': 0,'score_a': 304,'score_b': 334,'turn': B,'i': 2,'z': 19}

I want to make a dictionary of the string by using ast.literal_eval()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import ast
d = ast.literal_eval(txt)

This yields the following error:

{ValueError}malformed node or string: <_ast.Name object at
0x7fb8b8ab4fa0>

Please explain what’s going wrong? How can I make a dictionary from the string? Thanks

>Solution :

B is an undefined variable or unquoted string.

try:

txt = "{\'legs_a\': 1,\'legs_b\': 0,\'score_a\': 304,\'score_b\': 334,\'turn\': \'B\',\'i\': 2,\'z\': 19}"
d = ast.literal_eval(txt)
print(d)

Output:

{'legs_a': 1, 'legs_b': 0, 'score_a': 304, 'score_b': 334, 'turn': 'B', 'i': 2, 'z': 19}

Note if you wanted to deserialze the JSON string using json.loads() function then you would need to replace single quotes with double quotes.

data = json.loads(txt.replace("'", '"'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading