![]() |
Deep Copying ensures that modifications made to one copy don’t inadvertently affect the other. This concept is particularly important when we deal with nested data structures within dictionaries because shallow copies only create new references to the nested objects, which leads to potential unintended consequences. In this article, we will explore different approaches to create a Deep Copy of a dictionary In Python. Deep Copy of a Dict in PythonBelow are the possible approaches to creating a Deep Copy of a dict In Python
Deep Copy Of A Dict Using dict() ConstructorThe below approach code uses the dict() constructor to create a shallow copy of the original dictionary, allowing modifications to the original data to affect the copied dictionary (result). Python3
Output
Original Dictionary: {'website': 'GFG', 'topics': ['Algorithms', 'DSA', 'Python', 'ML']} Deep Copied Dictionary: {'website': 'GeeksforGeeks', 'topics': ['Algorithms', 'DSA', 'Python', 'ML']} Deep Copy Of A Dict Using copy ModuleThe below approach code uses copy.deepcopy from the copy module in Python to create an independent deep copy of a dictionary, making sure that modifications to the original dictionary do not affect the copied version. The resulting result dictionary retains the original state of the data. Python3
Output
Original Dictionary: {'website': 'GFG', 'topics': ['Algorithms', 'DSA', 'Python', 'ML']} Deep Copied Dictionary: {'website': 'GeeksforGeeks', 'topics': ['Algorithms', 'DSA', 'Python', 'ML']} Deep Copy Of A Dict Using Dictionary ComprehensionThe below approach code uses dictionary comprehension along with copy.deepcopy to create a deep copy of each key-value pair in the original dictionary. Modifications to the original dictionary (dict) do not impact the resulting result, demonstrating the preservation of the original state in the deep copy. Python3
Output
Original Dictionary: {'website': 'GFG', 'topics': ['Algorithms', 'DSA', 'Python', 'ML']} Deep Copied Dictionary: {'website': 'GeeksforGeeks', 'topics': ['Algorithms', 'DSA', 'Python', 'ML']} ConclusionIn conclusion, when working with dictionaries in Python, creating deep copies is crucial for maintaining data integrity, especially with nested structures. The above approaches using the copy module, dictionary comprehension, the json module, and the dict() constructor offer various methods to achieve this. Choosing the appropriate method depends on the complexity of the data, with copy.deepcopy() and json being preferable for handling nested structures, ensuring modifications to one copy do not inadvertently impact another. |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |