Can someone please explain this to me? This doesn\'t make any sense to me.
I copy a dictionary into another and edit the second and both are changed. Why is this hap
Every variable in python (stuff like dict1
or str
or __builtins__
is a pointer to some hidden platonic "object" inside the machine.
If you set dict1 = dict2
,you just point dict1
to the same object (or memory location, or whatever analogy you like) as dict2
. Now, the object referenced by dict1
is the same object referenced by dict2
.
You can check: dict1 is dict2
should be True
. Also, id(dict1)
should be the same as id(dict2)
.
You want dict1 = copy(dict2)
, or dict1 = deepcopy(dict2)
.
The difference between copy
and deepcopy
? deepcopy
will make sure that the elements of dict2
(did you point it at a list?) are also copies.
I don't use deepcopy
much - it's usually poor practice to write code that needs it (in my opinion).