We should first introduce variable assignment mechanism
Shallow copy
Existing data
data = {
"name":"alex",
"age":18,
"scores":{
"语文":130,
"数学":60,
"英语":98,
}
}
d2 = data
data["age"] = 20
print(d2)
You said the value of d2's print, age 18 or 20?
{'name': 'alex', 'age': 20, 'scores': {'语文': 130, '数学': 60, '英语': 98}}
看一下id
>>> print ( 'Assignment', id (data), id (d2))
Assignment 4439292336 4439292336
Why is it 20? Because d2 = data corresponding to just get the data memory address, but the data in each k, v is a separate memory address.
d2, data will always share the data in dict, as the situation does not occur before the string a = 1, b = a, a = 2, b is equal to 1 still.
If I really want a complete copy of the data dict how to do it?
You can use shallow copy syntax
data = {
"name":"alex",
"age":18,
"scores":{
"语文":130,
"数学":60,
"英语":98,
}
}
d2 = data.copy()
data["age"] = 20
print(d2)
print(data)
Export
{'name': 'alex', 'age': 18, 'scores': {'语文': 130, '数学': 60, '英语': 98}}
{'name': 'alex', 'age': 20, 'scores': {'语文': 130, '数学': 60, '英语': 98}}
id
>>> print('浅copy',id(data),id(d2))
Shallow copy 4440084720 4440087120
See id is the same, so the equivalent of 2 parts of independent data, but why this syntax is called a shallow copy of it? The change in the score you will know the value.
data = {
"name":"alex",
"age":18,
"scores":{
"语文":130,
"数学":60,
"英语":98,
}
}
d2 = data.copy()
data["age"] = 20
data["scores"]["数学"] = 77
print(d2)
print(data)
Look output, it is amazing, the value of two Dict in age is independent, but dictionaries score a point value is seemingly shared
{'name': 'alex', 'age': 18, 'scores': {'语文': 130, '数学': 77, '英语': 98}}
{'name': 'alex', 'age': 20, 'scores': {'语文': 130, '数学': 77, '英语': 98}}
id
Print >>> (ID (Data [ "Scores"]), ID (D2 [ "Scores"])) # the second hierarchy data
4440080288 4440080288
Because the shallow copy will copy only the first layer of data dict, deeper still scores below the value of a share.
Deep copy
If you want to completely make the above two dict completely independent, no matter how many layers there are data. Then use a python tool bag of tools,
>>> import copy
>>> d2 = copy.deepcopy(data)
>>> print('深copy',id(data),id(d2))
Deep copy 4439292336 4440080288
>>> data["age"] = 20
>>> data["scores"]["数学"] = 77
>>> print(d2)
{ 'Name': 'alex', 'age': 18, 'scores': { 'Language': 130, 'mathematics': 60, 'English': 98}}
>>> print(data)
{ 'Name': 'alex', 'age': 20, 'scores': { 'Language': 130, 'mathematics': 77, 'English': 98}}
Print >>> (ID (Data [ "Age"]), ID (D2 [ "Age"])) # first layer data
4434787728 4434787664
Print >>> (ID (Data [ "Scores"]), ID (D2 [ "Scores"])) # the second hierarchy data
4440087120 4440896528