Home > Backend Development > Python Tutorial > How to Properly Duplicate Dictionaries in Python and Avoid Modifying the Original?

How to Properly Duplicate Dictionaries in Python and Avoid Modifying the Original?

DDD
Release: 2024-12-22 17:32:10
Original
514 people have browsed it

How to Properly Duplicate Dictionaries in Python and Avoid Modifying the Original?

Duplicating Dictionaries: Preserving Originality

When assigning one dictionary to another in Python, it's important to remember that references are created, not copies. This means that any changes made to the assigned dictionary (the copy) will also affect the original dictionary. To prevent this behavior, a true copy of the dictionary must be created.

Consider the following example:

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

After assigning dict2 to dict1, changes made to dict2 are reflected in dict1 as well. To avoid this, an explicit copy must be made:

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

Alternatively, copy() method can be used:

dict2 = dict1.copy()
dict2["key2"] = "WHY?!"
print(dict1)  # {'key2': 'value2', 'key1': 'value1'}
Copy after login

By using either of these methods, changes made to the copied dictionary (dict2) will not affect the original dictionary (dict1).

The above is the detailed content of How to Properly Duplicate Dictionaries in Python and Avoid Modifying the Original?. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template