Join Regular Classroom : Visit ClassroomTech

copy() method in Python Dictionary

It is a method in python that copies all the content of the dictionary to a new dictionary. It returns a new dictionary and it doesn’t modify the old dictionary. Any modification of the new dictionary (copied dictionary) will not affect the old dictionary.

Syntax:

new_dictionary = old_dictionary.copy()

Don’t know what is clear in Python? Read: clear() in Python Dictionary

Example 1:

s = {0:"CodeWindow", 1:"India", 2:"News"}
x = s.copy()
print(x)

Output:

{0: ‘CodeWindow’, 1: ‘India’, 2: ‘News’}

Explanation:

Here it copied the dictionary(s) to dictionary(x) and prints the newly copied dictionary.

Example 2:

s = {"site":"CodeWindow", "country":"India", "type":"News", "platform":"IT"}
x = s.copy()
x["color"] = "black"
print("new_dict", x)
print("old_dict", s)

Output:

new_dict {‘site’: ‘CodeWindow’, ‘country’: ‘India’, ‘type’: ‘News’, ‘platform’: ‘IT’, ‘color’: ‘black’}
old_dict {‘site’: ‘CodeWindow’, ‘country’: ‘India’, ‘type’: ‘News’, ‘platform’: ‘IT’}

Explanation:

Here any change to the new dictionary did not affect the old dictionary.


You Missed

Also Checkout