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

Increment number in JSON file with python

I’m learing on how json files work, and I was tryng to make something that I thought it was simple, but I’ve been having problems, I have this code:

import json

id = 696969969696
warns = 10

with open('warn.json', 'r', encoding='utf-8') as f:
    guilds_dict = json.load(f)
    guilds_dict[str(id)] = warns

with open('warn.json', 'w', encoding='utf-8') as f:
    json.dump(guilds_dict, f, indent=4, ensure_ascii=False)

That when is executed adds id and warns to the JSON file looking like this:

{
    "696969969696": "10"
}

So, I wanted to do that in case that id already exists adds the numbers that warn has, here is an example:

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

id = 696969969696
warns = 2
{
    "696969969696": "10"
}

after executed:

{
    "696969969696": "12"
}

How can I do this, and if it’s possible i would like to understand it not only copy paste.
Thanks!

>Solution :

Firstly, two notes:

  • Once the json is loaded, it is a regular python dictionary. This operation is essentially unrelated to json.
  • id is already a function in python, used to get the memory address of an object. It’s generally recommended to avoid overriding builtins; consider using id_ instead.

That said, there are at least three ways to do this:

guilds_dict[str(id)] = guilds_dict.get(str(id), 0) + warns

where guilds_dict.get(str(id), 0) gets the value if it already exists, or 0 otherwise, then adds the new value.

from collections import defaultdict
guilds_dict = defaultdict(int, gilds_dict)
guilds_dict[str(id)] += warns

where a defaultdict is a dictionary that automatically fills with 0 if the key is gotten before it is set.

if str(id) in guilds_dict:
    guilds_dict[str(id)] += warns
else:
    guilds_dict[str(id)] = warns

where str(id) in guilds_dict checks if the key exists.

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