Home > Blockchain >  How to update key of dictionary inside a JSON file?
How to update key of dictionary inside a JSON file?

Time:04-04

This is an example of what's in my JSON file:

 "person1": {
        "name": "Henry",
        "email": "none",
        "friends_amt": {
            "male": 0,
            "female": 0
         }

How would I change the male's key (which is 0) and add one using " =" in python? I wan a command to update the key of male or female. I don't want to CHANGE 0 into 1, but I want to " =" to that 0 so that I can update it over an over again. Please help, I am working on a project, Thanks

I tried to use:

with open("people.json", "w") as f:
  data = json.load(f)

data["person1"]["friends_amt", "male"]  = 1

but it obviously failed and I expected that because my json knowledge is low and I took a wild guess

CodePudding user response:

You wanna use data["person1"]["friends_amt"]["male"] instead of with a comma :)

Since ['friends_amt'] is a dictionary in itself, you would use the selector you did with ['person1'] and ['friends_amt']

Hope this helps!

CodePudding user response:

for changing a key value in json, you need to load the json file (which turns it into a python dict) change the value in the dict then re-write it to the file :

import json

with open("myfile.json", "r") as jsonFile:
  data = json.load(jsonFile)

data["person1"]["friends_amt"]["male"]  = 1

with open("myfile.json", "w") as jsonFile:
  json.dump(data, jsonFile)

and notice that i used data["person1"]["friends_amt"]["male"] instead of what you used, that because your using a nested json structure. so you first need to get into the first key using data["person1"] which returns 2 keys, that there values are strings, and 1 that has another json structure inside of it (friend_amt). so to access the data in that, we need to go into it like we did with person1 so data["person1"]["friend_amt"]["male"]

  • Related