我有两个python字典,我将写入一个json文件。
{“音频”:[{“ fs”:“ 8000”,“持续时间”:“ 240”}]}
{“ ref”:[{“ end”:“ 115.63”,“ start”:“ 111.33”},{“ end”:“ 118.49”, “ start”:“ 117”}]}
我将它们合并如下;
dict={}
dict["audio"]=[{"fs":"8000", "duration": "240"}]
dict1={"audio":dict["audio"]}
dict["ref"]={"ref": [{"end": "115.63", "start": "111.33"}, {"end": "118.49", "start": "117"}]}
dict2={"ref":dict["ref"]}
dict={"audio":dict["audio"]}, {"ref":dict["ref"]}
当我写入json文件时,我得到如下输出;
with open("a.json", 'w') as fout:
json.dump((dict), fout)
[” {“音频”:[{“ fs”:“ 8000”,“持续时间”:“ 240”}] } , {“ ref”:{“ ref”: [{“ end”:“ 115.63”,“ start”:“ 111.33”},{“ end”:“ 118.49”,“ start”: “ 117”}]}} ]
我想将输出作为一本词典;
我想要的输出:
{“音频”:[{“ fs”:“ 8000”,“持续时间”:“ 240”}],“参考”:[{“开始”: “ 111.33”,“ end”:“ 115.63”},{“ start”:“ 117”,“ end”:“ 118.49”}, {“开始”:“ 119.31”,“结束”:“ 122.02”}]}
我用粗体字写了上面两个输出之间的区别。 (还有额外的“ []”和“ {}”)。
答案 0 :(得分:1)
尝试一下
import json
audio = {"audio": [{"fs": "8000", "duration": "240"}]}
ref = {"ref": [{"end": "115.63", "start": "111.33"}, {"end": "118.49", "start": "117"}]}
json.dumps({**audio, **ref})
from collections import OrderedDict
audio = {"audio": [{"fs": "8000", "duration": "240"}]}
ref = {"ref": [{"end": "115.63", "start": "111.33"}, {"end": "118.49", "start": "117"}]}
json.dumps(OrderedDict({**audio, **ref}))
答案 1 :(得分:0)
尽管我不确定您要做什么,但这可能会回答您的问题,请不要将usin dict用作变量名,因为它是python中的关键字。
import json
a={}
a["audio"]=[{"fs":"8000", "duration": "240"}]
a1={"audio":a["audio"]}
a["ref"]= [{"end": "115.63", "start": "111.33"}, {"end": "118.49", "start": "117"}]
a2={"ref":a["ref"]}
a={"audio":a["audio"], "ref":a["ref"]}
with open("a.json", 'w') as fout:
json.dump(a, fout)