Python Dictionary (Dictionary) copy () method

Source: Internet
Author: User
Tags shallow copy

Python Dictionary (Dictionary) copy () method description

The Python dictionary (Dictionary) copy () function returns a shallow copy of a dictionary.

Grammar

Copy () method syntax:

Dict.  Copy()  
Parameters
    • NA.
return value

Returns a shallow copy of a dictionary.

Instance

The following example shows how the copy () function is used:

Instance#!/usr/bin/python Dict1= {‘Name‘ ' zara age7}; dict2 = dict1 copy ( Span class= "hl-reserved" >print "New Dictinary:%s "% str (dict2

The result of the above example output is:

Newdictinary:{' age ':7,' Name ':' Zara '}   
The difference between direct assignment and copy

This can be illustrated by the following examples:

Instance#!/usr/bin/python #-*-Coding:utf-8-*- Dict1= {‘User‘:‘Runoob‘,‘Num‘:[1,2,3]}Dict2=Dict1 # Shallow copy: Reference object Dict3=Dict1.Copy() # Shallow copy: Deep copy Parent object (First level directory), sub-object (level two directory) not copy, or reference # Modify Data Dict1[‘User‘]=‘Root‘ dict1[ ' Num ]. Remove (1 Span class= "hl-comment" ># output print ( dict1) Print (dict2) print ( Dict3

The dict2 in the instance is actually a reference (alias) of the Dict1, so the output is consistent, dict3 the parent object is deeply copied, does not change with the Dict1 modification, the sub-object is a shallow copy, so modify with the Dict1.

{' Num ': [2, 3], ' User ':  ' root ' }{ ' Num ' : [2  3],  ' user ' :  ' root ' } { "num ' : [2 , 3], :  ' Runoob ' }      

Python Dictionary (Dictionary) copy () method

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.