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
DDDOriginal
2024-12-22 17:32:10489browse

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'}

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'}

Alternatively, copy() method can be used:

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

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:
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