Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading