0

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

MesTor
  • 15
  • 1
  • 5

2 Answers2

1

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}))
sushanth
  • 8,275
  • 3
  • 17
  • 28
  • Output is `{"ref": [{"end": "115.63", "start": "111.33"}, {"end": "118.49", "start": "117"}], "audio": [{"fs": "8000", "duration": "240"}]}`. "ref" and "audio" dictionary changed their places. Why this is happening? I could not understand. – MesTor Jul 09 '20 at 08:48
  • From python 3.6 dict maintains insertion order if you using lower version then you will need to use ``OrderedDict``, [refer this](https://stackoverflow.com/a/39537308/4985099) – sushanth Jul 09 '20 at 08:51
0

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)
  • My output like this:`{"ref": [{"end": "115.63", "start": "111.33"}, {"end": "118.49", "start": "117"}], "audio": [{"fs": "8000", "duration": "240"}]}`. Format is correct but "ref" and "audio" dictionary changed their places. Do you have any idea why? – MesTor Jul 09 '20 at 08:42
  • Can you share the code? or is it the exact same thing I posted? – Sumedh Rao Jul 09 '20 at 08:52