Add to dictionary file in json, python

So, I have a file python_dictionary.json

that contains a dictionary that I want to add, without having to open it every time. Let's say it python_dictionary.json

only contains:

{
    key1: value`
}

      

and I want to add

new_dictionary=
    {
        key2:value2
    }

      

Now I am doing:

with open('python_dictionary.json','a') as file:
    file.write(json.dumps(new_dictionary,indent=4))

      

This creates a dictionary like:

{
    key1:value1
}
{
    key2:value2
}

      

which is obviously not a real dictionary.

I know this: Add values ​​to an existing json file without overwriting it

but this is about adding one entry, I want to do json.dumps

+3


source to share


1 answer


It looks like you want to load a dictionary from json, add new key values ​​and write it back. If so, you can do this:

with open('python_dictionary.json','r+') as f:
    dic = json.load(f)
    dic.update(new_dictionary)
    json.dump(dic, f)

      

( 'r+'

read and write mode , not added because you are overwriting the whole file)



If you want to do the add along with json.dumps, I think you will have to remove the first one {

from the json.dumps line before adding. Something like:

with open('python_dictionary.json','a') as f:
    str = json.dumps(new_dictionary).replace('{', ',', 1)
    f.seek(-2,2)
    f.write(str)

      

+5


source







All Articles