Use the assignment operator to shallow copy a dictionary into another in Python. But if you want to use deep copy then use the deepcopy() method.
Example copy a dictionary into another in Python
Simple example code assign dict2 = dict1
, not making a copy of dict1
, it results in dict2
being just another name for dict1
.
Changing dict1 will reflect on dict2 because both dictionary object has the same reference.
dict1 = {"key1": "value1", "key2": "value2"}
dict2 = dict1
dict1['key1'] = "zero"
print(dict2)
Output: {‘key1’: ‘zero’, ‘key2’: ‘value2’}
To copy the mutable types like dictionaries, use copy
/ deepcopy
of the copy
module.
import copy
dict1 = {"key1": "value1", "key2": "value2"}
dict2 = copy.deepcopy(dict1)
dict1['key1'] = "zero"
print(dict2)
Output:
The advantage of using copy.copy()
or .copy()
is that it performs a shallow copy, meaning it creates a new dictionary object, but the values within the dictionary are still references to the same objects in memory. If you modify the values of the original or copied dictionary, the changes will be reflected in both dictionaries.
Do comment if you have any doubts or suggestions on this Python dictionary topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.