目标:将字符串列表转换为词典列表
我有以下字符串列表
info = ['{"contributors": null, "truncated": true, "text": "hey there"}',
'{"contributors": null, "truncated": false, "text": "how are you"}',
'{"contributors": 10, "truncated": false, "text": "howdy"}']
期望的输出:
desired_info = [{"contributors": null, "truncated": true, "text": "hey there"},
{"contributors": null, "truncated": false, "text": "how are you"},
{"contributors": 10, "truncated": false, "text": "howdy"}]
问题:如何将字符串列表转换为字典列表?
答案 0 :(得分:6)
您可以使用json.loads
:
import json
info = ['{"contributors": null, "truncated": true, "text": "hey there"}',
'{"contributors": null, "truncated": false, "text": "how are you"}',
'{"contributors": 10, "truncated": false, "text": "howdy"}']
info = [json.loads(x) for x in info]
print(info)
输出:
[{'contributors': None, 'truncated': True, 'text': 'hey there'}, {'contributors': None, 'truncated': False, 'text': 'how are you'}, {'contributors': 10, 'truncated': False, 'text': 'howdy'}]
答案 1 :(得分:0)
所以,如果你这样做:
>>> x = ['{"hi": True}']
>>> y = eval(x[0])
>>> y.get("hi")
True
理论上如此
desired_info = []
for x in info:
desired_info.append(eval(x))
应该这样做。
我不确定使用eval有多正确,但我相信如果不是,我会有人填写。