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



Now I am doing:

with open('python_dictionary.json','a') as file:


This creates a dictionary like:



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


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)
    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),2)




All Articles