Home >Backend Development >Python Tutorial >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)
This method creates a new dictionary that is an exact copy of dict1.
Method 2: Using dict1.copy()
dict2 = dict1.copy()
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'}
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!