Python dictionary copy () method

Source: Internet
Author: User
Tags shallow copy

The copy () method of the Python dictionary surface is deep copy ah, obviously Independent

1 d = {'a'b': 2}2 c = d.copy ()  3print('d=%s  c=%s' % (d, c))
Code1

Results:

D={' A ': 1, ' B ': 2} c={' A ': 1, ' B ': 2}

Modify d to see if the C change is not.

1 d['a']=32print('d=%s  c=%s' % (d, c))
Code2

Results:

D={' A ': 3, ' B ': 2} c={' A ': 3, ' B ': 2}

Here is still the same

Further changes:

 1  d = { " b  : 2,   a  : 3,    C  : ["   A  ,    C   " ]}   b = D.copy ()  3  print  ( d=%s b=%s   ' % (d, b) 
Code3
1 d['C'] = ['a','C' ' Shallow ' ]2print('d=%s  b=%s' % (d, b))
Code4

Code4 to d[' C ') and found that the results are not the same

D={' A ': 3, ' C ': [' a ', ' C ', ' shallow '], ' B ': 2} b={' A ': 3, ' C ': [' a ', ' C '], ' B ': 2}

However, the modification here is to re-assign the value, if it is directly modified it?

1D = {'b': 2,'a': 3,'C': ['a','C']}2b =d.copy ()3 4d['C'].append (123)5 Print('d=%s b=%s'% (d, b))
CODE5

Results:

d={' B ': 2, ' C ': [' a ', ' C ', 123], ' A ': 3} b={' B ': 2, ' C ': [' a ', ' C ', 123], ' A ': 3}

Found that the two are not completely independent, this is the origin of "shallow copy".

So, here's the question: Why is C not changed when you re-assign to D, and C changes when you modify D directly?

In the final analysis, Python is a mechanism problem because assignment operations are all referenced.

Start D,c reference the same dictionary, and when the D is re-assigned, C also points to the original dictionary, but the D reference has changed, so both are independent.

However, when I modify the value of C directly on the basis of the original dictionary (a list).

At this time d,c still the dictionary, so both have changed.

Python dictionary copy () method

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.