How can i merge two different python dictionary into single one?

Question:

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 "{ }" ).

Asked By: MesTor

||

Answers:

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)
Answered By: Sumedh Rao

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})

Python version < 3.6

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}))
Answered By: sushanth
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.