This article mainly introduces about the change of the value of the dictionary append to list in Python, has a certain reference value, now share to everyone, the need for friends can refer to
See an example
d={' test ': 1}d_test=dd_test[' test ']=2print D
If you practice at the command line, you'll notice that you're changing the d_test, but D has changed as well.
Usually this is not the same as what we expected.
Why?
Because dictionary d is an object, D_test=d does not actually create the dictionary in memory again. It just points to the same object. This is also a consideration for Python to improve performance and optimize memory.
Actual scenario
d={"name": "}l=[]for I in Xrange (5): d[" name "]=i l.append (d) Print L
Loops may not be the same as the results you want.
Even though the append is in the list, the list contains an object, or a dictionary address. Rather than the real storage space in memory.
Use the. Copy () method. Can create a new stand-alone dictionary
d={"name": "}l=[]for I in Xrange (5): test=d.copy () test[" name "]=i l.append (test) print L
Update:
a={' Q ': 1, ' W ': []}b=a.copy () b[' Q ']=2b[' W '].append (123) print Aprint b
At this point, the value of ' Q ' in a does not change, but the value in the list has changed.
Because copy is a shallow-level copy
But there's a track here.
a={' Q ': 1, ' W ': []}b=a.copy () b[' Q ']=2b[' W ']=[123]print aprint b
If you assign a value directly, it will not change the structure in a (mostly the relationship of the Append method).
In-depth copy
Import copya={' Q ': 1, ' W ': []}b=copy.deepcopy (a)