我在python 3中有两个字典,称为a和b,当它们作为JSON转储时如下所示:
a = {"person": 26.94, "car": 99.49, "dog": 50.56}
b = {"filename": "1234.jpg", "model": "model1", "prototxt": "prototxt.txt"}
我需要将这些组合成下面的JSON格式,但我在python中的方法有点迷失,所以欢迎任何指针!
{
"payload": {
"config": [{
"model": "model1",
"filename": "1234.jpg",
"prototxt": "prototxt.txt"
}],
"results": [{
"object": "person",
"value": 26.94
},
{
"object": "car",
"value": 99.49
},
{
"object": "dog",
"value": 50.56
}
]
}
}
答案 0 :(得分:2)
您可以通过以下代码实现此目的:
a = {"person": 26.94, "car": 99.49, "dog": 50.56}
b = {"filename": "1234.jpg", "model": "model1", "prototxt": "prototxt.txt"}
a_list= []
for record in a:
a_list.append({'object':record, 'value':a[record]})
payload = {'config':[b], 'results':a_list}
data = {"payload":payload}
# You can print this in the terminal/notebook with
print json.dumps(data, indent=4)
# Or save with
json_string = json.dumps(data)
with open('/path/to/file/payload.json', 'w') as outfile:
json.dump(data, outfile)
这是在字典中输入条目并将其打包成字符串以添加到新的更高级词典中的问题。