Writing a List of Dictionaries to seperate JSONs

I do have dictionary, with each value as a list.

I want to write individual items to separate JSON files.
For example

data_to_write = {"Names":["name1", "name2", "name3"], "email":["mail1", "mail2", "mail3"]}

Now I want 3 jsons i.e data1.jsob, data2.json, data3.json in the following(approx) format.

data1.json

{
    Name: name1,
    email: mail1
}

data2.json

{
    Name: name2,
    email: mail2
}

and so on.

My current approach is


    for file_no in range(no_of_files):
        for count, (key, info_list) in enumerate(data_to_write.items()):
            for info in info_list:
                with open(
                     os.path.join(self.path_to_output_dir, str(file_no)) + ".json",
                     "a",
                ) as resume:
                    json.dump({key: info}, resume)

But this is wrong. Any helps appreciated.

>Solution :

You could use pandas to do the work for you. Read the dictionary into a dataframe, then iterate the rows of the dataframe to produce the json for each row:

import pandas as pd

data_to_write = {"Names":["name1", "name2", "name3"], "email":["mail1", "mail2", "mail3"]}
df = pd.DataFrame(data_to_write).rename(columns={'Names':'Name'})
for i in range(len(df)):
   print(df.iloc[i].to_json())

Output:

{"Name":"name1","email":"mail1"}
{"Name":"name2","email":"mail2"}
{"Name":"name3","email":"mail3"}

You can write the separate JSON elements to different files in the way described in @AndrejKesely answer.

Leave a Reply