Home > Net >  how to add multiple dictionary to a json file in python?
how to add multiple dictionary to a json file in python?

Time:12-24

How can I add multiple dictionary in a JSON file? I want to add 1 or 2 dictionaries once and after a while to add 1 or 2 or 3 dictionaries in same JSON file.

Exemple:

 dict1 = {'a': 1, 'b':2}

-> I want to add it to a 'test.json' file and after a while I want to add the dictionary

 dict2 = {'c': 1, 'd':2}
 dict3 = {'e': 1, 'f':2}

-> and after a while I want to add this 2 for example

EDIT

import json
dict1 = {'a': 1, 'b': 1}
dict2 = {'c': 2, 'd': 2}
dict3 = {'e': 3, 'f': 3}
list1 = []
list1.append(dict1)
with open('testjson_dict.json', 'a') as f:
    json.dump(list1, f)

-> this is first output

[
    {
        "a": 1,
        "b": 1
    }
]

-> than I append dict2 to list1, and this is the output, it create a second list and put dict2 in it, how can i change the code to put dict2 in my first list?

[
    {
        "a": 1,
        "b": 1
    }
][
    {
        "c": 2,
        "d": 2
    }
]

CodePudding user response:

I am assuming you want to store these dicts as a list in json, so the final result would be:

[
  {'a': 1, 'b':2}, 
  {'c': 1, 'd':2}, 
  {'e': 1, 'f':2}
]

Here is a possible workflow. Start with dict_list = [dict1].

  1. Make sure you import json. Write dict_list to test.json
    with open('test.json', 'w', encoding='utf-8') as json_file:
        json.dump(dict_list, json_file)
  1. Read the contents of test.json into a Python list.
    with open('test.json', encoding='utf-8') as json_file:
        dicts = json.load(json_file)
  1. Add dict2 and dict3 to the list you just read in.
  2. Overwrite test.json with the resulting list (like in step 1).

Now test.json should incude a list of the 3 dicts.

CodePudding user response:

You can concat the new data as a list with in that way:

import json
# write first file
dict_list = [{'a': 1, 'b':2}]
with open('test.json', 'w', encoding='utf-8') as json_file:
    json.dump(dict_list, json_file)

# concat to readed file and overvwrite
with open('test.json', encoding='utf-8') as json_file:
    dicts = json.load(json_file)
dicts  = [{'c': 1, 'd':2}, {'e': 1, 'f':2}] # list concatenation operation
with open('test.json', 'w', encoding='utf-8') as json_file:
    json.dump(dicts, json_file)
  • Related