Python copy dictionary into another | Example code

Use assign operator to shallow copy dictionary into another in Python. But if you want to use deep copy then use the deepcopy() method.

Example copy 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 on 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:

Python copy dictionary into another

Do comment if you have any doubts and suggestions on this Python dictionary topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.