Why are my dictionaries changing values when I change only one of them?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By _NotH

So I have code that is similar to something like this:

var dict1 = {"value" : 1}
var dict2 = dict1

func _ready():
    print(dict1, dict2)
    dict2["value"] += 2
    print(dict1, dict2)

The first time, it prints the expected: {value:1}{value:1}
However, after changing dict2’s value, it prints: {value:3}{value:3}

So my question is: why did dict1 also change values if I only wrote for it to happen with dict2?
And more importantly: how do I avoid this from happening?

:bust_in_silhouette: Reply From: kidscancode

Because that’s how dictionaries work - they are passed by reference. dict2 and dict1 are both references to the same dictionary object.

If you want dict2 to be a unique dictionary, you have to make a copy:

var dict1 = {"value" : 1}
var dict2 = dict1.duplicate()

Oh, I didn’t know that! Thank you

_NotH | 2022-07-20 00:52