Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update key of dictionary inside a JSON file?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading