Home > Backend Development > Python Tutorial > How to Create True Copies of Python Dictionaries?

How to Create True Copies of Python Dictionaries?

Susan Sarandon
Release: 2024-12-29 07:11:14
Original
733 people have browsed it

How to Create True Copies of Python Dictionaries?

Preserving Original Dictionaries: Separating Copies from Origin

When working with Python dictionaries, it's crucial to understand that assignment doesn't create copies. Assigning one dictionary to another, as in dict2 = dict1, establishes both variables as references pointing to the same dictionary object. Consequently, modifications to either dictionary affect both.

The Solution: Explicit Copying

To avoid this behavior and preserve the original dictionary, explicit copying is necessary. Python offers two methods for achieving this:

Method 1: Using dict(dict1)

dict2 = dict(dict1)
Copy after login

This method creates a new dictionary that is an exact copy of dict1.

Method 2: Using dict1.copy()

dict2 = dict1.copy()
Copy after login

This method also generates a new dictionary that is a duplicate of dict1.

Demonstration

To illustrate the difference between reference and copy, consider the following example:

dict1 = {"key1": "value1", "key2": "value2"}

# Copy dict1 using dict(dict1)
dict2 = dict(dict1)
dict2["key2"] = "WHY?!"
print(dict1)  # Output: {'key1': 'value1', 'key2': 'value2'}

# Copy dict1 using dict1.copy()
dict3 = dict1.copy()
dict3["key2"] = "CHANGED!"
print(dict1)  # Output: {'key1': 'value1', 'key2': 'value2'}
Copy after login

In this example, dict2 and dict3 refer to separate dictionaries. Modifying either copy doesn't affect the original dictionary dict1.

The above is the detailed content of How to Create True Copies of Python Dictionaries?. 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