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

Question:

I am trying to convert a string type to its equivalent Dictionary form:

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

Error:

"JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)"
Asked By: user3924913

||

Answers:

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

You need to add the keys as strings in double quotes.

Answered By: Abhishek Mittal

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

Answered By: JaySean
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.