The copy () method of the Python dictionary surface is deep copy ah, obviously Independent
1 d = {'a'b': 2}2 c = d.copy () 3print('d=%s c=%s' % (d, c))
Code1
Results:
D={' A ': 1, ' B ': 2} c={' A ': 1, ' B ': 2}
Modify d to see if the C change is not.
1 d['a']=32print('d=%s c=%s' % (d, c))
Code2
Results:
D={' A ': 3, ' B ': 2} c={' A ': 3, ' B ': 2}
Here is still the same
Further changes:
1 d = { " b : 2, a : 3, C : [" A , C " ]} b = D.copy () 3 print ( d=%s b=%s ' % (d, b)
Code3
1 d['C'] = ['a','C' ' Shallow ' ]2print('d=%s b=%s' % (d, b))
Code4
Code4 to d[' C ') and found that the results are not the same
D={' A ': 3, ' C ': [' a ', ' C ', ' shallow '], ' B ': 2} b={' A ': 3, ' C ': [' a ', ' C '], ' B ': 2}
However, the modification here is to re-assign the value, if it is directly modified it?
1D = {'b': 2,'a': 3,'C': ['a','C']}2b =d.copy ()3 4d['C'].append (123)5 Print('d=%s b=%s'% (d, b))
CODE5
Results:
d={' B ': 2, ' C ': [' a ', ' C ', 123], ' A ': 3} b={' B ': 2, ' C ': [' a ', ' C ', 123], ' A ': 3}
Found that the two are not completely independent, this is the origin of "shallow copy".
So, here's the question: Why is C not changed when you re-assign to D, and C changes when you modify D directly?
In the final analysis, Python is a mechanism problem because assignment operations are all referenced.
Start D,c reference the same dictionary, and when the D is re-assigned, C also points to the original dictionary, but the D reference has changed, so both are independent.
However, when I modify the value of C directly on the basis of the original dictionary (a list).
At this time d,c still the dictionary, so both have changed.
Python dictionary copy () method