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.
filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

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

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

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


My Personal Notes arrow_drop_up

pawanasipugmailcom

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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


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