Home > Backend Development > Python Tutorial > Why Doesn\'t Updating a Shallow Copy of a Dictionary Change the Original?

Why Doesn\'t Updating a Shallow Copy of a Dictionary Change the Original?

Barbara Streisand
Release: 2024-12-01 11:21:10
Original
358 people have browsed it

Why Doesn't Updating a Shallow Copy of a Dictionary Change the Original?

Why Updating "Shallow" Copy Dictionary Doesn't Update "Original" Dictionary?

Understanding Shallow Copying

When creating a shallow copy of a dictionary, the dictionary object is not copied entirely. Instead, a new reference to the original object is created. This means that any changes made to the shallow copy will also be reflected in the original dictionary.

Example: Dictionary

Consider the following example:

original = dict(a=1, b=2)
new = original.copy()
new.update({'c': 3})
Copy after login

In this case, new is a shallow copy of original. When new is updated with {'c': 3}, the original dictionary remains unchanged because both original and new reference the same underlying object.

Contrast with Shallow Copying in Lists

Lists behave differently when shallow copied. When creating a shallow copy of a list, a new reference to the underlying list object is created. However, any changes made to the shallow copy do not affect the original list, as lists are mutable objects that can be modified independently.

Understanding Deep Copying

Unlike shallow copying, deep copying creates a new, independent copy of the original object. This means that any changes made to the deep copy will not affect the original object.

Solution

To update the original dictionary, it is necessary to create a deep copy instead of a shallow copy. The following code uses copy.deepcopy() to create a deep copy:

import copy
new = copy.deepcopy(original)
new.update({'c': 3})
Copy after login

Now, original remains untouched while new has the updated values.

The above is the detailed content of Why Doesn\'t Updating a Shallow Copy of a Dictionary Change the Original?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template