How to deep copy a dictionary in Python

To perform a deep copy of a dictionary (dict) in Python, we can make use of the deepcopy() function from the copy module.

import copy

original_dict = {
    'city': 'Chicago',
    'temp_forecast_week': [11, 11, 8, 12, 12, 11, 10],
    'metadata': {'version': 'v1.0'}

# Deep copy example
deep_copied_dict = copy.deepcopy(original_dict)

# Modify the deep copied dict
deep_copied_dict['temp_forecast_week'] = [15, 11, 8, 12, 12, 11, 10]

# Print both dictionaries
print("Original Dict:", original_dict)
print("Deep Copied Dict:", deep_copied_dict)
Deep copy a dictionary in Python Example

Reference documentation:

Python copy module documentation:

Python copy.deepcopy() function documentation:

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap