Home » Python

How to copy a dictionary and only edit the copy in Python?

Python dictionary: Here, we are going to learn how to copy a dictionary and only edit the copy in Python?
Submitted by Sapna Deraje Radhakrishna, on January 19, 2020

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.

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'}

To copy a dictionary, either uses a shallow copy or deep copy approach, as explained in the below example.

Using shallow copy

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 deep copy

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'}






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.