Python3 Dictionary copy() Method
Description
The Python dictionary copy() function returns a shallow copy of the dictionary.
Syntax
Syntax of the copy() method:
dict.copy()
Parameters
- NA。
Return Value
Returns a shallow copy of the dictionary.
Example
The following example demonstrates how to use the copy() function:
Example
#!/usr/bin/python3
dict1 = {'Name': 'Example', 'Age': 7, 'Class': 'First'}
dict2 = dict1.copy()
print ("The newly copied dictionary is:",dict2)
The output result of the above example is:
新复制的字典为 : {'Age': 7, 'Name': 'Example', 'Class': 'First'}
Difference between direct assignment and copy
This can be explained by the following example:
Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
dict1 = {'user':'example','num':[1,2,3]}
dict2 = dict1 # Shallow copy: references object
dict3 = dict1.copy() # Shallow copy: the parent object (first-level directory) is deeply copied, the child object (second-level directory) is not copied, and the child object is a reference
# Modify the data
dict1['user']='root'
dict1['num'].remove(1)
# Output result
print(dict1)
print(dict2)
print(dict3)
In the example, dict2 is actually a reference (alias) to dict1, so the output results are consistent; dict3 has a deep copy of the parent object, so it will not be modified with dict1, while the child object is a shallow copy, so it will be modified with dict1.
{'user': 'root', 'num': [2, 3]}
{'user': 'root', 'num': [2, 3]}
{'user': 'example', 'num': [2, 3]}
Knowledge Extension
Analysis of Python direct assignment, shallow copy, and deep copy
Other Extensions
Python3 Dictionary