【问题标题】:Turn list of strings into list of dictionaries python将字符串列表转换为字典列表python
【发布时间】:2018-03-04 01:47:28
【问题描述】:

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

我有以下字符串列表

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

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

【问题讨论】:

    标签: python string dictionary


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      如果你这样做:

      >>> x = ['{"hi": True}']
      >>> y = eval(x[0])
      >>> y.get("hi")
      True
      

      理论上是这样

      desired_info = []
      for x in info:
          desired_info.append(eval(x))
      

      应该可以解决问题。

      我不确定使用 eval 是否合适,但如果不是,我相信有人会填写。

      【讨论】:

      • 如果他的所有值都是有效的 Python,这样的方法会起作用。不幸的是,他没有在输入中使用 python 布尔值。
      • 如果语法上有效的 Python 代码是对象文字,最好使用 ast.literal_eval。没有必要允许任意代码执行。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-24
      • 2016-12-05
      • 1970-01-01
      • 2011-07-12
      • 2014-05-23
      • 2019-05-29
      相关资源
      最近更新 更多