Python Dictionary copy()

They copy() method returns a shallow copy of the dictionary.

Syntax:

dict.copy()

Parameters:

The copy() method doesn't take any parameters.

Returns:

This method doesn't modify the original
dictionary just returns copy of the dictionary.

Examples:



Input : original = {1:'geeks', 2:'for'}
        new = original.copy()
Output : original:  {1: 'one', 2: 'two'}
         new:  {1: 'one', 2: 'two'}

Error:

As we are not passing any parameters 
there is no chance of any error.
# Python program to demonstrate working
# of dictionary copy
original = {1:'geeks', 2:'for'}

# copying using copy() function
new = original.copy()

# removing all elements from the list
# Only new list becomes empty as copy()
# does shallow copy.
new.clear()

print('new: ', new)
print('original: ', original)

Output:

new:  {}
original:  {1: 'geeks', 2: 'for'}

How is it different from simple assignment “=”?
Unlike copy(), the assignment operator does deep copy.

# Python program to demonstrate difference
# between = and copy()
original = {1:'geeks', 2:'for'}

# copying using copy() function
new = original.copy()

# removing all elements from new list
# and printing both
new.clear()
print('new: ', new)
print('original: ', original)

original = {1:'one', 2:'two'}

# copying using =
new = original

# removing all elements from new list
# and printing both
new.clear()
print('new: ', new)
print('original: ', original)

Output:

new:  {}
original:  {1: 'geeks', 2: 'for'}
new:  {}
original:  {}



There is a difference between I CAN and CAN I email pawanasipugmailcom phone 7278786219

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Article Tags :
Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



2 Average Difficulty : 2/5.0
Based on 1 vote(s)