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

converting a string like '{100-101:[405-874, 405-863], 100-100:[405-862, 405-865]} to dictionary in python

I am trying to convert a string of following type to its equivalent Dictionary form, Please help me with the solution.

sample_str='{100-101:[405-874, 405-863], 100-100:[405-862, 405-865]}’
dict_str=json.loads(sample_str)

Error that its returing:
"JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)"

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

>Solution :

There are two ways to solve it,

Type 1:
Considering the input format is correct which you have mentioned, then the code is

import yaml
s = '{100-101:[405-874, 405-863], 100-100:[405-862, 405-865]}'
d = yaml.load(s, Loader=yaml.Loader)
d

enter image description here

Type 2: The usual way
Here, the input has to be modified slightly to make it string key: value pair
e.g. test_string = ‘{"100-101":"[405-874, 405-863]", "100-100":"[405-862, 405-865]"}’

Then the code is

import json
test_string = '{"100-101":"[405-874, 405-863]", "100-100":"[405-862, 405-865]"}'
print("The original string : " + str(test_string))
res = json.loads(test_string)
res

enter image description here

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