Python3 Att Dictionary Copy
# Python3.x Python3 Dictionary copy() Method
[ Python3 Dictionary](#)
* * *
## Description
The Python dictionary copy() function returns a shallow copy of a dictionary.
## Syntax
The syntax for the copy() method is:
dict.copy()
## Parameters
* NA.
## Return Value
Returns a shallow copy of the dictionary.
## Example
The following example demonstrates the usage of the copy() function:
## Example
#!/usr/bin/python3 dict1 = {'Name': 'Tutorial', 'Age': 7, 'Class': 'First'} dict2 = dict1.copy()print("The newly copied dictionary is: ",dict2)
The output of the above example is:
The newly copied dictionary is: {'Age': 7, 'Name': 'Tutorial', 'Class': 'First'}
* * *
## Difference Between Direct Assignment and copy
This can be illustrated with the following example:
## Example
#!/usr/bin/python# -*- coding: UTF-8 -*-dict1 = {'user':'tutorial','num':[1,2,3]} dict2 = dict1# Shallow copy: reference object dict3 = dict1.copy()# Shallow copy: deep copy of the parent object (first level), child objects (second level) are not copied, child objects are references# Modify data dict1['user']='root'dict1['num'].remove(1)# Print results print(dict1)print(dict2)print(dict3)
In the example, dict2 is actually a reference (alias) of dict1, so the output results are the same. dict3 has a deep copy of the parent object, so it does not change with modifications to dict1, but the child objects are shallow copied, so they change with modifications to dict1.
{'user': 'root', 'num': [2, 3]}{'user': 'root', 'num': [2, 3]}{'user': 'tutorial', 'num': [2, 3]}
### Knowledge Extension
[Analysis of Python Direct Assignment, Shallow Copy, and Deep Copy](#)
* * Python3 Dictionary](#)
YouTip