Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a dictionary and only edit the copy

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'} 
like image 245
MadSc13ntist Avatar asked Mar 17 '10 21:03

MadSc13ntist


People also ask

How do you copy a dictionary?

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.

Can you modify a 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.

How do I make a deep copy of a dictionary?

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.


2 Answers

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() 
like image 188
Mike Graham Avatar answered Sep 20 '22 03:09

Mike Graham


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) 
like image 31
Imran Avatar answered Sep 23 '22 03:09

Imran