Skip to main content
 首页 » 编程设计

python之将字符串列表转换为字典列表 python

2025年05月04日25webabcd

目标:将字符串列表转换为字典列表

我有以下字符串列表

 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"}] 

问题:如何将字符串列表转换为字典列表?

请您参考如下方法:

你可以使用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'}]