python:从多个列表中创建json

时间:2018-03-12 10:02:18

标签: python json

我在python中有以下变量:

常量:

  • d [ “ID”]

阵列

  • d [ “时间”]
  • d [ “X”]
  • d [ “Y”]
  • d [ “z” 的

需要在以下视图中获取json:

{"data_list":[{"id":1,"time":"1","x":1,"y":1,"z":1}, {"id":1,"time":"2","x":2,"y":2,"z":2}]}

我已经完成了迭代。 什么是最快的方式?

1 个答案:

答案 0 :(得分:1)

import json

d = {'id' : 1, 'time' : ['1', '2'], 'x' : ['1', '2'], 'y' : ['1', '2'], 'z' : ['1', '2']}
print(json.dumps({'data_list': [{'id' : d['id'], 'time' : t, 'x' : x, 'y' : y, 'z' : z} for t, x, y, z in zip(d['time'], d['x'], d['y'], d['z'])]}, indent=2))

会为您提供以下JSON输出:

{
  "data_list": [
    {
      "id": 1,
      "time": "1",
      "x": "1",
      "y": "1",
      "z": "1"
    },
    {
      "id": 1,
      "time": "2",
      "x": "2",
      "y": "2",
      "z": "2"
    }
  ]
}

可替换地:

from operator import itemgetter
import json

d = {'id' : 1, 'time' : ['1', '2'], 'x' : ['1', '2'], 'y' : ['1', '2'], 'z' : ['1', '2']}
arr = ['time', 'x', 'y', 'z']

print(json.dumps({'data_list': [dict([('id', d['id'])] + list(zip(arr, v))) for v in zip(*itemgetter(*arr)(d))]}, indent=2))