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 happening?
>>> dict1 = {"key1": "value1", "key2": "value2"} >>> dict2 = dict1 >>> dict2 {'key2': 'value2', 'key1': 'value1'} >>> dict2["key2"] = "WHY?!" >>> dict1 {'key2': 'WHY?!', 'key1': 'value1'}
The dict. copy() method returns a shallow copy of the dictionary. The dictionary can also be copied using the = operator, which points to the same object as the original. So if any change is made in the copied dictionary will also reflect in the original dictionary.
Yes you can, dictionary is an mutable object so they can be modified within functions, but it must be defined before you actually call the function.
deepcopy() To make a deep copy, use the deepcopy() function of the copy module. In a deep copy, copies are inserted instead of references to objects, so changing one does not change the other.
Python never implicitly copies objects. When you set dict2 = dict1
, you are making them refer to the same exact dict object, so when you mutate it, all references to it keep referring to the object in its current state.
If you want to copy the dict (which is rare), you have to do so explicitly with
dict2 = dict(dict1)
or
dict2 = dict1.copy()
When you assign dict2 = dict1
, you are not making a copy of dict1
, it results in dict2
being just another name for dict1
.
To copy the mutable types like dictionaries, use copy
/ deepcopy
of the copy
module.
import copy dict2 = copy.deepcopy(dict1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With