-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshallow__VS_deep.py
44 lines (37 loc) · 1.17 KB
/
shallow__VS_deep.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import copy
company = {
"IT": [
{"name": "John", "projects": ["projectA", "projectB"]},
{"name": "Jane", "projects": ["projectC"]}
],
"HR": [
{"name": "Doe", "projects": ["onboarding", "recruitment"]}
]
}
# Using a shallow copy
shallow_company = copy.copy(company)
shallow_company["Tech"] = shallow_company.pop("IT")
# Modifying an employee's projects in the new structure
shallow_company["Tech"][0]["projects"].append("projectD")
print(shallow_company)
print(company)
# Result: ['projectA', 'projectB', 'projectD']
# Problem: The original company structure is affected!
# Resetting our example
company = {
"IT": [
{"name": "John", "projects": ["projectA", "projectB"]},
{"name": "Jane", "projects": ["projectC"]}
],
"HR": [
{"name": "Doe", "projects": ["onboarding", "recruitment"]}
]
}
# Using a deep copy
deep_company = copy.deepcopy(company)
deep_company["Tech"] = deep_company.pop("IT")
# Modifying an employee's projects in the new structure
deep_company["Tech"][0]["projects"].append("projectD")
print(company["IT"][0]["projects"])
# Result: ['projectA', 'projectB']
# Success: The original company structure remains unaffected!