Sep
Sep

Reputation: 1

Is there a way in python to add values into a key instead of replacing the existing values in json file?

is there a way to add another value into a key instead of replacing it in json file using python? I tried using 'a' instead of 'w', but it created a different set of dictionary and I got an error message saying Json only allow one top level value

import json
    web=input('web:')
    username=input('us:')
    pw=input('pw')
    account_data= {web: {'Email': username,'Password': pw}}
    try:
        with open('trial.json', 'r') as file:
            # save the previous data in json
            data = json.load(file)
            # update the json by appending the newer data into old data
            data.update(account_data)
    
    except FileNotFoundError:
        with open('trial.json', 'w') as file:
            # create data.json if it doesnt exist
            json.dump(account_data, file, indent=4)
    else:
        with open('trial.json', 'w') as file:
            # replace old json file with new one
            json.dump(data, file, indent=4)

output:

{
    "face": {
        "Email": "asdqweerqr",
        "Password": "dregtertsdf"
    },
    "fasd": {
        "Email": "wqe",
        "Password": "asdf"
    }
}

the output always replaces the existing key,value pair. Thanks

Upvotes: 0

Views: 337

Answers (1)

Serge
Serge

Reputation: 3765

Basically you cannot modify the key of a python dictionary. Yet it is easy is to delete old key. Since json module represent a json object with a dictionary, that's basically the only option.

See the discussion Change the name of a key in dictionary

It is not so uncommon in python to create a completely new dictionary from the old one, but deleting unneeded keys is both easier and more efficient.

PS. There are some fancy python json library that would let you change a json key. Also, in pandas and JavaScript, you can easily modify json keys. Another easy hack is first serialize dictionary into string, replace the key, and save the string into the file, but that can get tricky in corner cases.

Upvotes: 1

Related Questions