How to Copy a Dictionary to Another Dictionary in Python?

Estimated read time 1 min read

To copy a dictionary to another dictionary in Python, you can use the copy() method or the dictionary assignment (=) operator. Here are two examples:

Example 1: Using the copy() method to create a shallow copy of the dictionary:

source_dict = {'key1': 'value1', 'key2': 'value2'}
destination_dict = source_dict.copy()

print(destination_dict)  # Output: {'key1': 'value1', 'key2': 'value2'}

In this example, the copy() method is called on the source_dict to create a shallow copy, which is assigned to the destination_dict.

Example 2: Using the assignment (=) operator to copy the dictionary:

source_dict = {'key1': 'value1', 'key2': 'value2'}
destination_dict = source_dict

print(destination_dict)  # Output: {'key1': 'value1', 'key2': 'value2'}

In this example, the source_dict is directly assigned to the destination_dict using the assignment (=) operator. Note that this creates a reference, so any modifications made to one dictionary will affect the other.

Choose the approach that best suits your needs. If you need an independent copy of the dictionary, use the copy() method. If you want both dictionaries to refer to the same object, use the assignment (=) operator.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply