Copy problem with "Python" dict

Source: Internet
Author: User

Part of the Source: http://blog.sina.com.cn/s/blog_5c6760940100bmg5.html

① Direct Assignment----result is a reference to a different name

The modification of the new dictionary has a full effect on the original dictionary, just a reference to the relationship

>>> C = {'a': 1,'b': 2}>>> d =C>>> d['e']=3>>>d{'a': 1,'b': 2,'e': 3}>>>c{'a': 1,'b': 2,'e': 3}>>> f =dict ()>>> f =D>>> f["k"]=4>>>f{'a': 1,'k': 4,'b': 2,'e': 3}>>>c{'a': 1,'k': 4,'b': 2,'e': 3}

② uses the copy () function---shallow copy.

If a dictionary has a reference type, such as list, replication copies its references only and does not copy its values:

>>> d = {'names': ['Bob','Sam']}>>> y =d.copy ()>>> y['names'][0] ='Jack'>>>y{'names': ['Jack','Sam']}>>>d{'names': ['Jack','Sam']}

③ Deep Copy Deepcopy

>>> fromCopyImportdeepcopy>>> d = {'names': ['Bob','Sam']}>>> y =Deepcopy (d)>>> y['names'][0] ='Jack'>>>d{'names': ['Bob','Sam']}>>>y{'names': ['Jack','Sam']}

Copy problem with "Python" dict

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.