我有一个词典列表,它看起来像这样:
[{'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}]
问题是现在,它被格式化为字符串。换句话说,当我尝试遍历列表中的项目时,我只获得单个字符。有没有办法将其转换回“词典列表”类型?
答案 0 :(得分:4)
使用ast.literal_eval
将字符串转换为python对象(安全地):
>>> 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}]
答案 1 :(得分:1)
你的意思是你有类似的东西:
x = "[{'T': 13472}, {'A': 13472}]"
然后你可以随时简单地评估它,假设源是安全的。看看: