This article mainly introduces a brief discussion on the change of value after dictionary append to list in python. It has certain reference value. Now I share it with everyone. Friends in need can refer to it
Look at an example
d={'test':1} d_test=d d_test['test']=2 print d
If you practice it on the command line, you will find that what you changed is d_test, but d also Changes followed.
Usually this is not what we expect.
Why?
Because dictionary d is an object, and d_test=d does not actually create the dictionary again in memory. 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
The result after loop may not be the same as what you want.
Even if appended to the list, what is stored in the list is still an object, or the address of the dictionary. rather than the actual storage space in memory.
Use the .copy() method. A new independent dictionary can be created
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']=2 b['w'].append(123) print a print b
a={'q':1,'w':[]} b=a.copy() b['q']=2 b['w']=[123] print a print b
Deep copy
import copy a={'q':1,'w':[]} b=copy.deepcopy(a)
Python creates an empty list, And an explanation of append usage
The above is the detailed content of A brief discussion on the change of value after dictionary append to list in Python. For more information, please follow other related articles on the PHP Chinese website!