How to convert a String to a dictionary list

Viewed 56

Let's say we have String like this:

string = "[{'Chr': 'chrX', 'Start': 107844640, 'End': 107844640}, {'Chr': 'chrY', 'Start': 107844641, 'End': 107844641}]"

The goal is to convert that string into a list of dictionaries.

For now I have only managed to convert the String into a list:

str1 = string.replace(']','').replace('[','')
l = str1.replace('"','').split(",")

Unfortunately this adds unwanted characters like '""', how could I get rid of the undesired characters and get the desired result?

3 Answers
import ast

string = "[{'Chr': 'chrX', 'Start': 107844640, 'End': 107844640}, {'Chr': 'chrY', 'Start': 107844641, 'End': 107844641}]"

# ast.literal_eval(string)

for i in ast.literal_eval(string):
    print(i)

My immediate solution, and as Mark Tolonen says, ast.literal_eval(string) is the most built-in pythonic way without using exec().

Ok, I'll jump on the stealing wagon as well, as it seems the OP didn't fully get the "answer".

So, you basically already have a list of dictionaries, just defined in a variable of type string. Use ast to get the literal value from the string and voila, a list of dictionaries.

import ast

dict_string = "[{'Chr': 'chrX', 'Start': 107844640, 'End': 107844640}, {'Chr': 'chrY', 'Start': 107844641, 'End': 107844641}]"
dict_list = ast.literal_eval(dict_string)

# dict_list is now a list of dictionaries

Related