Python dictionary deep copy and shallow copy

Source: Internet
Author: User

#!/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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.