Python Dict Copy vs Deepcopy

Aug 1, 2019

Copy

Shallow copy

data = {    'name': 'Desmond',    'friends': ['Jack', 'Mei Ru', 'Bob']}data2 = data.copy()data2['name'] = 'New Desmond'data2['friends'][0] = 'New Jack'print(data)

Output

{'name': 'Desmond', 'friends': ['New Jack', 'Mei Ru', 'Bob']}

NOTE: data['name'] does not change as the value is copied, but data['friends'] is an object/list where the value is not copied.

Deep Copy

import copydata = {    'name': 'Desmond',    'friends': ['Jack', 'Mei Ru', 'Bob']}data2 = copy.deepcopy(data)data2['name'] = 'New Desmond'data2['friends'][0] = 'New Jack'print(data)

Output

{'name': 'Desmond', 'friends': ['Jack', 'Mei Ru', 'Bob']}

NOTE: Both data['name'] and data['friends'] as deepcopy make a copy of basic value and object/list.

NOTE: copy and deepcopy are not thread-safe, use lock.

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.