【问题标题】:Python: Combine multiple lists into one JSON arrayPython:将多个列表组合成一个 JSON 数组
【发布时间】:2019-12-19 20:38:43
【问题描述】:

我想将多个列表合并到一个 JSON 数组中。 这是我的两个列表:

address =  ['address1','address2']
temp = ['temp1','temp2']

我通过以下调用合并两个列表并创建一个 JSON。

new_list = list(map(list, zip(address, temp)))
jsonify({
    'data': new_list
})

这是我的通话结果:

{
    "data": [
        [
            "address1",
            "temp1"
        ],
        [
            "address2",
            "temp2"
        ]
    ]
}

但是,我想收到以下问题。我该怎么做以及如何插入标识符addresshello

{
    "data": [
        {
            "address": "address1",
            "temp": "temp1"
        },
        {
            "address": "address2",
            "temp": "temp2"
        }
    ]
}

【问题讨论】:

    标签: json python-3.x list dictionary merge


    【解决方案1】:

    您可以像这样更改现有代码。 lambda 函数可以将其转换为字典。

    address =  ['address1','address2']
    temp = ['temp1','temp2']
    
    new_list = list(map(lambda x : {'address': x[0], 'temp': x[1]}, zip(address, temp)))
    
    jsonify({
        'data': new_list
    })
    
    

    【讨论】:

      【解决方案2】:

      您可以使用列表理解:

      import json
      
      address =  ['address1','address2']
      temp = ['temp1','temp2']
      
      d = {'data': [{'address': a, 'temp': t} for a, t in zip(address, temp)]}
      
      print( json.dumps(d, indent=4) )
      

      打印:

      {
          "data": [
              {
                  "address": "address1",
                  "temp": "temp1"
              },
              {
                  "address": "address2",
                  "temp": "temp2"
              }
          ]
      }
      

      【讨论】:

      • 酷就这么简单。我本可以自己想出来的。非常感谢您的帮助。真的很棒。
      猜你喜欢
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      • 2022-06-15
      • 2019-05-28
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      • 2019-07-03
      相关资源
      最近更新 更多