Python dictionary Method - copy()

www.‮tfigi‬idea.com

The copy() method is a built-in dictionary method in Python that returns a shallow copy of a dictionary. The copy() method creates a new dictionary with the same key-value pairs as the original dictionary, but the new dictionary is a separate object with its own memory address.

Here's the syntax for the copy() method:

new_dict = my_dict.copy()

Here's an example:

# create a dictionary
my_dict = {'apple': 2, 'banana': 3, 'cherry': 4}

# create a copy of the dictionary
new_dict = my_dict.copy()

# modify the original dictionary
my_dict['apple'] = 5

# print both dictionaries
print(my_dict)
print(new_dict)

Output:

{'apple': 5, 'banana': 3, 'cherry': 4}
{'apple': 2, 'banana': 3, 'cherry': 4}

In this example, we create a dictionary my_dict with three key-value pairs, and then call the copy() method to create a new dictionary new_dict that is a shallow copy of the original dictionary. We then modify the value associated with the key 'apple' in the original dictionary, and print both dictionaries. We can see that the value of 'apple' in the original dictionary has changed to 5, but the value of 'apple' in the new dictionary remains unchanged at 2.

The copy() method is useful when you need to create a new dictionary that has the same key-value pairs as an existing dictionary, but you want to modify the new dictionary without affecting the original dictionary. It can also be used to create a backup copy of a dictionary before making changes to it. Note that the copy() method creates a shallow copy of the dictionary, which means that any mutable objects that are values in the dictionary are still references to the same objects in memory. If you need a deep copy of a dictionary that creates new copies of all mutable objects, you can use the copy.deepcopy() function from the copy module.