On the change of the value of dictionary append to list in Python

Source: Internet
Author: User
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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.