Python Dictionary copy() method
Description
Python Dictionary copy() function returns a shallow copy of a dictionary.
Syntax
Syntax of the copy() method:
dict.copy()
Parameters
- NA。
Return Value
Returns a shallow copy of a dictionary.
Examples
The following example demonstrates the use of the copy() function:
Example
#!/usr/bin/python
dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = dict1.copy()
print "New Dictinary : %s" % str(dict2)
The output of the above example is:
New Dictinary : {'Age': 7, 'Name': 'Zara'}
Difference between direct assignment and copy
This can be illustrated by the following example:
Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
dict1 = {'user':'example','num':[1,2,3]}
dict2 = dict1 # Shallow copy: reference object
dict3 = dict1.copy() # Shallow copy: deep copies the parent object (first-level directory), but does not copy the child object (second-level directory); it is still a reference
# Modify 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) of dict1, so the output results are the same. dict3's parent object is deep-copied and will not change with dict1's modifications, but the child object is shallow-copied, so it changes with dict1's modifications.
{'num': [2, 3], 'user': 'root'}
{'num': [2, 3], 'user': 'root'}
{'num': [2, 3], 'user': 'example'}
Knowledge Extension
Python direct assignment, shallow copy and deep copy analysis
Other Extensions
Python Dictionary