SoFunction
Updated on 2024-11-17

The problem of changing the value of a dictionary append to a list in python.

Look at an example

d={'test':1}
d_test=d
d_test['test']=2
print d

If you practice at the command line, you'll see that you changed d_test , but d changed along with it.

Usually this is not what we expect.

Why?

Because the dictionary d is an object, and d_test=d doesn't really create the dictionary again in memory, it just points to the same object. It just points to the same object, which is a performance and memory optimization feature of python.

real-life scenario

d={"name":""}
l=[]
for i in xrange(5):
  d["name"]=i
  (d)
print l

The result of the loop may not be the same as what you want.

Even if you append to a list, what is stored in the list is an object, or a dictionary address. It is not a real storage space in memory.

Use the .copy() method. A new standalone dictionary can be created

d={"name":""}
l=[]
for i in xrange(5):
  test=()
  test["name"]=i
  (test)
print l

Updated:

a={'q':1,'w':[]}
b=()
b['q']=2
b['w'].append(123)
print a
print b

At this point it turns out that the value of 'q' in a doesn't change but the values in its list change anyway

Because copy is a shallow copy

But there's a track here.

a={'q':1,'w':[]}
b=()
b['q']=2
b['w']=[123]
print a
print b

A direct assignment does not change the structure in a (mostly due to the append method)

Deep copy

import copy
a={'q':1,'w':[]}
b=(a)

Above this talk about python dictionary append to the list after the value of the change of the problem is all I share with you, I hope to give you a reference, but also hope that you support me more.