Python Dict Copy vs Deepcopy

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

data = {
    '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:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.