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

How to save a dictionary and a list in the same json file with python?

I wish to save a dictionary and a list in one json file so that when I parse the file I could distinguish them.
This is the function I use to save the dictionary in the json file:

def save_callback():
    #folder = filedialog.askdirectory()
    file = filedialog.asksaveasfilename()
    with open(file,'w') as file:
        file.write(json.dumps(test_dict))
    os.rename(file.name,file.name + ".txt")

What should I add to this function to save the list too?

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

>Solution :

Since JSON objects can be arbitrarily nested, the easiest solution is to store both the dict and the list inside another object:

data = json.dumps([test_dict, test_list])

Then you can load it like this:

test_dict, test_list = json.loads(data)
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