0

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!

Zeninツ
  • 175
  • 1
  • 9
  • Probably several ways, easiest is to use `if` to see if the key already exists. There are also improved dictionary structures where values default to whatever you want, so you can just use + blindly – Barry Carter Jul 14 '22 at 15:20

2 Answers2

3

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.

Anonymous12358
  • 436
  • 1
  • 10
0

first off you should check out the documentation on dictionaries.

From the documentation:

To check whether a single key is in the dictionary, use the in keyword.

So you can do if str(id) in guilds_dict. Then you will need to handle the addition of the two values (which I notice are strings so be careful there).

Charmander35
  • 115
  • 1
  • 11