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: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

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