使用逗号分隔的字典生成json转储



我正在从python生成json文件,但是,我想在每个循环后用逗号分隔字典,下面是代码的一部分:

listA = [computer1,computer2]
listB = [computertype1,computertype2]
for computer, item in zip(listA,listB):
mydict = {
"Computertype": "somevalue",
"computer": [ 
computer
],
"targert": {
"item": item
}
},

所需输出应为:

[
{
"Computertype": "somevalue",
"computer": [ 
computer1
],
"targert": {
"item": computertype1
}
},
{
"Computertype": "somevalue",
"computer": [ 
computer2
],
"targert": {
"item": computertype2
}
}
]

所以基本上在第一个循环的第一个结束大括号后面有一个逗号:},所有这些都在一个列表中,一个括号在顶部,一个右括号在底部。

当运行代码时,它不会在循环中的每个大括号后显示逗号,而且它会自动在列表中输入每个循环,有什么建议吗?

我得到的:

[  {
"Computertype": "somevalue",
"computer": [ 
computer1
],
"targert": {
"item": computertype1
}
}
]
[   {
"Computertype": "somevalue",
"computer": [ 
computer2
],
"targert": {
"item": computertype2
}
}]

我想这就是您想要的:

listA = [computer1,computer2]
listB = [computertype1,computertype2]
mylist = []
for computer, item in zip(listA,listB):
mydict = {
"Computertype": "somevalue",
"computer": [ 
computer
],
"target": {
"item": item
}
}
mylist.append(mydict)
print(mylist)

最新更新