#!/usr/bin/python
#-*-Coding:utf-8-*-
Import Copy
Dict1 = {' user ': ' vickey ', ' num ': [1, 2, 3], ' age ': {' a ': ' 1 ', ' B ': ' 2 '}}
Dict2 = Dict1 # Any operation on the original data will affect the replication
# Shallow copy and deep copy operation of data first
Dict3 = Dict1.copy () # Shallow copy: The first level is a reference object, level two is a copy; The two-level directory of the original data has changed, and the two-level directory of the shallow replicated data changes, but the first-level directory is unchanged
Dict4 = Copy.deepcopy (dict1) # deep copy: Deep copy Parent object (First level directory), sub-object (Level two directory) is a reference, non-copy; simply, it's exactly the same as the original data.
# Modify Data
dict1[' user '] = ' root '
dict1[' num '].remove (3)
dict1[' num '].append (6)
dict1[' age ' [' a '] = ' 111 '
# After the data is copied, the deep copy and shallow copy are no different, they are the changed data
# dict3 = Dict1.copy ()
# Dict4 = copy.deepcopy (Dict1)
# Output Results
Print (DICT1)
Print (DICT2)
Print (DICT3)
Print (DICT4)
Print results
{' age ': {' a ': ' 111 ', ' B ': ' 2 '}, ' num ': [1, 2, 6], ' user ': ' Root '}
{' age ': {' a ': ' 111 ', ' B ': ' 2 '}, ' num ': [1, 2, 6], ' user ': ' Root '}
{' age ': {' a ': ' 111 ', ' B ': ' 2 '}, ' num ': [1, 2, 6], ' user ': ' Vickey '}
{' age ': {' a ': ' 1 ', ' B ': ' 2 '}, ' num ': [1, 2, 3], ' user ': ' Vickey '}
Python dictionary deep copy and shallow copy