Home »
Python
How to copy a dictionary and only edit the copy in Python?
By Sapna Deraje Radhakrishna Last updated : December 21, 2024
Overview
Python never implicitly copies the dictionary or any objects. So, while we set dict2 = dict1, we're making them refer to the same dictionary object. Hence, even when we mutate the dictionary, all the references made to it, keep referring to the object in its current state.
Example
dict1 = {"key1": "abc", "key2": "efg"}
dict2 = dict1
print(dict1)
print(dict2)
dict2['key2'] = 'pqr'
print(dict1)
print(dict2)
Output
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'pqr'}
{'key1': 'abc', 'key2': 'pqr'}
How to copy a dictionary and only edit the copy?
To copy a dictionary and only edit the copy, you can use either use a shallow copy or a deep copy. A shallow copy constructs a new compound object and then inserts references into it to the objects found in the original. And, A deep copy constructs a new compound object and then recursively inserts the copies into it of the objects found in the original.
Using the shallow copy (copy() method)
By using the dictionary's copy() method, you can create a copy of the dictionary and make the changes in the copied dictionary.
Example
Consider the below program -
dict1 = {"key1": "abc", "key2": "efg"}
print(dict1)
dict3 = dict1.copy()
print(dict3)
dict3['key2'] = 'xyz'
print(dict1)
print(dict3)
Output
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'xyz'}
Using the deep copy (deepcopy() method)
By using the deepcopy() method of copy package, you can also create a copy of the dictionary and make the changes in the copied dictionary.
Example
Consider the below program -
import copy
dict1 = {"key1": "abc", "key2": "efg"}
print(dict1)
dict4 = copy.deepcopy(dict1)
print(dict4)
dict4['key2'] = 'test1'
print(dict4)
print(dict1)
Output
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'test1'}
{'key1': 'abc', 'key2': 'efg'}