0

The is the JSON file:

"name": {
        "money": 0,
        "email": "none",
        "list": ["yes", "no"], 
        "backpack": {
            "books": 0,
            "pens": 21

And this is what code I wrote:

# Directory of file
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, 'C:/Users/dado/files/example.json')

# Opening JSON file
with open(file_path, 'r') as f:
   data = json.load(f)

# Defining what total pens is
total_pens = data["name"]["backpack"]["pens"]

# Reducing 1 from total pens (for some reason does not update the file)
total_pens -= 1

# Dumping data (this is mandatory as I heard)           
with open(file_path, "w") as f:
   json.dump(data,f,indent=4)

# Rest of command below...

Why does "total_pens" in the JSON file not become 20 after I run the code? It should "-= 1" am I right? Please tell me what I did wrong...

I am stuck and do not know what to do

Hyperba
  • 89
  • 3
  • 12
  • 6
    you updated the variable `total_pens` not `data["name"]["backpack"]["pens"]`. The variable is not a pointer to the data in the dictionary, it makes a copy of the data. – Tom McLean Apr 04 '22 at 10:20
  • 1
    Did you mean: `data["name"]["backpack"]["pens"] -= 1`? – quamrana Apr 04 '22 at 10:20
  • use `data["name"]["backpack"]["pens"] -= 1` – kj-crypto Apr 04 '22 at 10:22
  • Thank you people so much - it works now, but why can't I just update the variable if it is the same thing? – Hyperba Apr 04 '22 at 10:23
  • 3
    Mandatory link to [Ned Batchelder](https://nedbatchelder.com/text/names.html) – quamrana Apr 04 '22 at 10:24
  • 1
    "why can't I just update the variable if it is the same thing?" Because that would mean causing the number `21` itself to change. `total_pens -= 1` does not change the object that represents the integer `21` - that cannot be changed from within Python. Instead, it computes the result, and tells `total_pens` to *stop being the same thing as* `data["name"]["backpack"]["pens"]`, and start being the result of the computation. – Karl Knechtel Apr 04 '22 at 10:36
  • 1
    It is just as if you had done `a = 21` and then `b = a` and then `b -= 1`. `a` will not change. – Karl Knechtel Apr 04 '22 at 10:37
  • 1
    @TomMcLean Assignment in Python **does not** copy. Python's variables are names - effectively what other languages would call pointers or references, depending. The actual reason for the behaviour is that Python's `int` type is immutable, and `-=` therefore does not mutate them. – Karl Knechtel Apr 04 '22 at 10:38

0 Answers0