1

I have a list of dictionaries, it looks something like this:

[{'T': 13472}, {'A': 13472}, {'C': 9866, 'T': 3606}, {'G': 13472}, {'G': 13472}, {'A': 221, 'C': 26, 'T': 12845, 'G': 380}, {'T': 13472}, {'A': 13472}, {'C': 546, 'T': 12926}, {'C': 13472}, {'A': 13472}, {'C': 10674, 'T': 2798}, {'C': 13472}, {'A': 13472}, {'C': 554, 'T': 12918}, {'C': 13472}, {'A': 13472}]

The issue is right now, it's formatted as a string. In other words, when I try to iterate through the items in the list, I get only individual characters. Is there a way to convert it back into a "list of dictionaries" type?

4

2 回答 2

5

Use ast.literal_eval to convert a string to a python object(safely):

>>> from ast import literal_eval
>>> strs = "[{'T': 13472}, {'A': 13472}, {'C': 9866, 'T': 3606}, {'G': 13472}, {'G': 13472}, {'A': 221, 'C': 26, 'T': 12845, 'G': 380}, {'T': 13472}, {'A': 13472}, {'C': 546, 'T': 12926}, {'C': 13472}, {'A': 13472}, {'C': 10674, 'T': 2798}, {'C': 13472}, {'A': 13472}, {'C': 554, 'T': 12918}, {'C': 13472}, {'A': 13472}]"
>>> literal_eval(strs)
[{'T': 13472}, {'A': 13472}, {'C': 9866, 'T': 3606}, {'G': 13472}, {'G': 13472}, {'A': 221, 'C': 26, 'T': 12845, 'G': 380}, {'T': 13472}, {'A': 13472}, {'C': 546, 'T': 12926}, {'C': 13472}, {'A': 13472}, {'C': 10674, 'T': 2798}, {'C': 13472}, {'A': 13472}, {'C': 554, 'T': 12918}, {'C': 13472}, {'A': 13472}]
于 2013-09-06T16:34:02.537 回答
2

Do you mean you have something like:

x = "[{'T': 13472}, {'A': 13472}]"

Then you could always simply evaluate it, assuming the source is safe. Have a look at:

于 2013-09-06T16:36:22.490 回答