我有3个列表,
city_id = [1,2,3]
city_name = ['a','b','c']
city_capital = ['x','y','z']
如何将以上三个列表组合成以下格式的json,而不需要自己迭代。是否有任何库函数可以在python中完成工作?
[
{
'city_id': 1,
'city_name': 'a',
'city_capital': 'x'
},
{
'city_id': 2,
'city_name': 'b',
'city_capital': 'y'
},
{
'city_id': 3,
'city_name': 'c',
'city_capital': 'z'
}
]
答案 0 :(得分:4)
获取包含该格式数据的列表:
[ { 'city_id': x, 'city_name': y, 'city_capital': z }
for x, y, z in zip(city_id, city_name, city_capital) ]
如果您想以完全格式输出数据,那么您可以在评论中使用@AndyKubiak的建议:
import json
d = [ { 'city_id': x, 'city_name': y, 'city_capital': z }
for x, y, z in zip(city_id, city_name, city_capital) ]
pretty_json = json.dumps(d, sort_keys=True, indent=4)