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:
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.
idis already a function in python, used to get the memory address of an object. It’s generally recommended to avoid overriding builtins; consider usingid_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.