In this article we will learn about the Python dictionary
python copy functionThe relevant knowledge,
python copyWhat it means is that what he does will be answered in the next article.
Summary description
The Python dictionary (Dictionary) copy () function returns a shallow copy of a dictionary.
Grammar
Copy () method syntax:
Dict.copy ()
Parameters
NA.
return value
Returns a shallow copy of a dictionary.
Instance
The following example shows how the copy () function is used:
#!/usr/bin/pythondict1 = {' Name ': ' Zara ', ' Age ': 7};d Ict2 = Dict1.copy () print "New dictinary:%s"% str (DICT2)
The result of the above example output is:
New dictinary: {' age ': 7, ' Name ': ' Zara '}
The difference between direct assignment and copy
This can be illustrated by the following examples:
#!/usr/bin/python#-*-Coding:utf-8-*-dict1 = {' user ': ' runoob ', ' num ': [1, 2, 3]}dict2 = dict1 # Shallow copy: Reference object DICT3 = Dict1.copy () # Shallow copy: Deep copy Parent object (First level directory), sub-object (level two directory) not copy, or reference # Modify data dict1[' user '] = ' root ' dict1[' num '].remove (1) # Output print (dict1) print (dict2) print (DICT3)
The dict2 in the instance is actually a reference (alias) of the Dict1, so the output is consistent, dict3 the parent object is deeply copied, does not change with the Dict1 modification, the sub-object is a shallow copy, so modify with the Dict1.
{' num ': [2, 3], ' user ': ' Root '} {' num ': [2, 3], ' user ': ' Root '} {' num ': [2, 3], ' user ': ' Runoob '}