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: