Python 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/python
dict1
= {
'
Name
'
:
'
Zara
'
,
'
Age
'
:
7
};
dict2
=
dict1
.
copy
(
)
"
New Dictinary : %s
"
%
str
(
dict2
)
The output of the above example is:
New Dictinary : {'Age': 7, 'Name': 'Zara'}
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 copied deeply, while child objects (second level) are not copied and are still referenced.
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.
{'num': [2, 3], 'user': 'root'}
{'num': [2, 3], 'user': 'root'}
{'num': [2, 3], 'user': 'runoob'}
Knowledge extension
Python direct assignment, shallow copy and deep copy explained
Python Dictionary