Reputation: 15
I have two python dictionary and i will write into a single json file.
{"audio": [{"fs": "8000", "duration": "240"}]}
{"ref": [{"end": "115.63", "start": "111.33"}, {"end": "118.49", "start": "117"}]}
I merge them as followings;
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"]}
When i wrote into a json file, i get output as following;
with open("a.json", 'w') as fout:
json.dump((dict), fout)
[{"audio": [{"fs": "8000", "duration": "240"}]}, {"ref": {"ref": [{"end": "115.63", "start": "111.33"}, {"end": "118.49", "start": "117"}]}}]
I want to get output as one dictionary;
The output I want:
{"audio": [ {"fs": "8000", "duration": "240"}], "ref": [{"start": "111.33", "end": "115.63"}, {"start": "117", "end": "118.49"}, {"start": "119.31", "end": "122.02"}]}
I wrote as bold the difference between two output above. (There are extra "[ ]" and "{ }" ).
Upvotes: 0
Views: 76
Reputation: 8302
try this,
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}))
Upvotes: 1
Reputation: 3
Though I am not sure what you are trying to do, this may answer your question, and please refrain from usin dict as a variable name as it is a keyword in 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)
Upvotes: 0