【问题标题】:how to add keys to list and convert to json in python如何在python中将键添加到列表并转换为json
【发布时间】:2019-06-28 21:52:03
【问题描述】:

我已经尝试this 将列表列表转换为 json。但无法转换为正确的 json 格式。

我的数据是

    data= [['India',
          'India runs mentorship driven incubation.',
          '/7e9e130075d3bfcd9e0.png'],
         ['Capital',
          'develops high growth and market-defining India-centric Software and Services Big Data and Analytics and Consumer Mobile or Internet markets.',
          '/data/images/512bc5a2937.png']]

    titles = ['Country','description','logo']

    values = [e for g in grouper(3, data) for e in g]
keys = (titles[i%3] for i in xrange(len(values)))

objs = [dict(g) for g in grouper(3, list(izip(keys, values)))]
print(objs)

结果:

[{'Country': ['India', 'India runs mentorship driven incubation.', '/7e9e130075d3bfcd9e0.png'], 'description': ['Capital', 'develops high growth and market-defining India-centric Software and Services Big Data and Analytics and Consumer Mobile or Internet markets.', '/data/images/512bc5a2937.png']}]

但预期的结果应该是这种形式。

[{'Country': 'India', 'description': 'India runs mentorship driven incubation.', 'logo': '/7e9e130075d3bfcd9e0.png'}]  

应该是什么原因?

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    您可以使用单行列表推导式。首先,遍历数据,对于每条数据(entry),zip 它和titles 来创建一个可以转换成字典的元组的可迭代对象:

    data= [['India',
          'India runs mentorship driven incubation.',
          '/7e9e130075d3bfcd9e0.png'],
         ['Capital',
          'develops high growth and market-defining India-centric Software and Services Big Data and Analytics and Consumer Mobile or Internet markets.',
          '/data/images/512bc5a2937.png']]
    
    titles = ['Country','description','logo']
    
    result = [dict(zip(titles, entry)) for entry in data]
    print(result)
    

    输出:

    [{'Country': 'India',
      'description': 'India runs mentorship driven incubation.',
      'logo': '/7e9e130075d3bfcd9e0.png'},
     {'Country': 'Capital',
      'description': 'develops high growth and market-defining India-centric Software and Services Big Data and Analytics and Consumer Mobile or Internet markets.',
      'logo': '/data/images/512bc5a2937.png'}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-03
      • 2021-08-15
      • 2014-03-03
      • 2019-06-12
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 2012-04-03
      相关资源
      最近更新 更多