Python3 Dictionary copy() Method
Description
The Python dictionary copy() function returns a shallow copy of a dictionary.
Syntax
copy() method syntax:
dict.copy()
Parameters
- NA。
Return Value
Returns a shallow copy of a dictionary.
Example
The following example shows how to use the copy() function:
Example
#!/usr/bin/python3
dict1
= {
'
Name
'
:
'
Runoob
'
,
'
Age
'
:
7
,
'
Class
'
:
'
First
'
}
dict2
=
dict1
.
copy
(
)
(
"
The newly copied dictionary is:
"
,
dict2
)
The output of the above example is:
新复制的字典为 : {'Age': 7, 'Name': 'Runoob', 'Class': 'First'}
The difference between direct assignment and copy
This can be illustrated with the following example:
Example
#!/usr/bin/python
-- coding: UTF-8 --
dict1
= {
'
user
'
:
'
runoob
'
,
'
num
'
:
[
1
,
2
,
3
]
}
dict2
=
dict1
Shallow copy: reference object
dict3
=
dict1
.
copy
(
)
Shallow copy: the parent object (first level) is deep-copied, child objects (second level) are not copied and are references
Modify the data
dict1
[
'
user
'
]
=
'
root
'
dict1
[
'
num
'
]
.
remove
(
1
)
Output result
(
dict1
)
(
dict2
)
(
dict3
)
In the example dict2 is actually a reference (alias) of dict1, so the outputs are identical; dict3's parent object is deep-copied so it does not change when dict1 is modified, while the child object is a shallow copy so it changes with dict1.
{'user': 'root', 'num': [2, 3]}
{'user': 'root', 'num': [2, 3]}
{'user': 'runoob', 'num': [2, 3]}
Knowledge extension
Python direct assignment, shallow copy and deep copy explained
Python3 Dictionary