Home  >  Article  >  Backend Development  >  A brief discussion on the change of value after dictionary append to list in Python

A brief discussion on the change of value after dictionary append to list in Python

不言
不言Original
2018-05-04 14:13:532478browse

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

At this time, I found that the value of 'q' in a will not change, but the value in the list still changed

Because the copy is a shallow copy

But there is a track here

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

If assigned directly, the structure in a will not be changed (mostly due to the append method)

Deep copy

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

Related recommendations:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn