The copy() method creates a shallow copy of the current dictionary.

The shallow copy will contain the same key-value pairs as the original dictionary, but any changes made to the original dictionary will not be reflected in the copied dictionary.

Its syntax is as shown below:

new_dict = d.copy()

The copy() method does not take any parameters and returns a new dictionary that is a copy of the original dictionary.

fruits = {'apple': 5, 'banana': 10, 'orange': 3}

#create a shallow copy
copy_dict = fruits.copy()

print(copy_dict)

The  original dictionary and its copies are independent, adding or removing items from either will not affect the other.

fruits = {'apple': 5, 'banana': 10, 'orange': 3}

#create a shallow copy
copy_dict = fruits.copy()

#delete an item from 'fruits'
del fruits['banana']

#add an item item to 'copy_dict'
copy_dict['mango'] = 8 

print('original: ', fruits)
print('copy: ', copy_dict)

copy() with mutable objects

Note that the copy() method creates a shallow copy of the dictionary. This means that if the original dictionary contains mutable values, such as lists, sets dictionaries, e.t.c, the copied dictionary will contain references to those objects. Any changes made to the mutable objects in the original dictionary will be reflected in the copied dictionary and vice verse.

Note that in this sense, we are not modifying the dictionary itself but rather the mutable objects it references which also happens to be referenced by the copies of the dictionary.

students = {'John': ['Math', 'Science'], 'Lisa': ['English', 'Art']} 

# creating a copy of the dictionary 
copy_dict = students.copy() 

# append a subject to a student's list in the original dictionary 
students['John'].append('History') 

print(students)
print(copy_dict)

In the example above, we create a dictionary called "students" with lists as values. We then create a copy of it using the dict.copy() method. As you can see, when we append an item to a list value in the original dictionary,  the change is reflected in both dictionaries. The change would also have been reflected in the original dictionary if the change was made from the copy.

students = {'John': ['Math', 'Science'], 'Lisa': ['English', 'Art']} 

# creating a copy of the dictionary 
copy_dict = students.copy() 

#remove the last subject from John's list through copy_dict 
copy_dict['John'].pop() 

print(students)
print(copy_dict)