Describe
The Python Dictionary copy () method returns a shallow copy of a dictionary (parent invariant, child change).
Grammar
Copy () method syntax:
Dict.copy ()
Parameters
return value
Returns a shallow copy of a dictionary (the parent does not change, the child changes).
Instance
The following example shows how the copy () method is used:
#!/usr/bin/python3 Dict1 = {' Name ': ' Runoob ', ' age ': 7, ' Class ': ' first '} Dict2 = Dict1.copy () print ("Newly copied dictionary:", Dict2)
The result of the above example output is:
The newly copied dictionary is: {' age ': 7, ' Name ': ' Runoob ', ' Class ': ' First '}
The difference between a direct reference, a shallow copy, and a deep copy
This can be illustrated by the following examples:
#!/usr/bin/python#-*-coding:utf-8-*-import copydict1 = {' user ': ' runoob ', ' num ': [1, 2, 3]} # raw Data Dict2 = Dict1 # Direct reference: Dict2 and Dict1 all point to the same object. Dict3 = Dict1.copy () # Shallow copy: The parent object of DICT3 and Dict1 is a separate object, but their child objects still point to the same object. Dict4 = Copy.deepcopy (dict1) # deep copy: The whole of Dict4 and Dict1 is a separate object. dict1[' user '] = ' root ' # Modify parent dict1dict1[' num '].remove (1) # Modify Parent Object Dict1 [1, 2, 3] list sub-object print (' raw data: ', {' user ': ' Runoob ', ' Num ': [1, 2, 3]}) # Raw data print (' Changed data: ', Dict1) # Both parent modified print (' Direct reference: ', Dict2) # Father and son are changed (direct reference) print (' Shallow copy: ', DICT3) # Parent unchanged, child change (shallow copy) p Rint (' Deep copy: ', Dict4) # Father and son are unchanged (deep copy)
The dict2 in the instance is actually an assignment reference (alias) of Dict1, so the output is consistent, dict3 is a shallow copy of Dict1, the parent object is not modified with dict1 modification, and the sub-object changes with the Dict1; Dict4 is a deep copy of Dict1. Neither the parent nor the child objects are modified with Dict1 modification.
The output results are as follows:
Raw data: {' user ': ' runoob ', ' num ': [1, 2, 3]} changed data: {' user ': ' root ', ' num ': [2, 3]} Assignment reference: {' user ': ' root ', ' num ': [2, 3]} shallow copy: { ' User ': ' runoob ', ' num ': [2, 3]} deep copy: {' user ': ' runoob ', ' num ': [1, 2, 3]}
Knowledge expansion
Python direct assignment, shallow copy, and deep copy parsing
Python dictionary copy () method