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
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