Python Dictionary copy()
Python Dictionary copy() method returns a shallow copy of the dictionary.
Python Dictionary copy() Syntax:
dict.copy()
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Python Dictionary copy() Parameters:
The copy() method doesn’t take any parameters.
Python Dictionary copy() Returns:
This method doesn’t modify the original, dictionary just returns copy of the dictionary.
Python Dictionary copy() Examples:
Input : original = {1:'geeks', 2:'for'}
new = original.copy()
Output : original: {1: 'one', 2: 'two'}
new: {1: 'one', 2: 'two'}Python Dictionary copy() Error:
As we are not passing any parameters there is no chance of any error.
Example 1: Working with Python Dictionary copy()
Python3
# Python program to demonstrate working# of dictionary copyoriginal = {1: 'geeks', 2: 'for'}# copying using copy() functionnew = 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'}Example 2: Python Dictionary copy() and update
Python3
# given dictionarydict1 = {10: 'a', 20: [1, 2, 3], 30: 'c'}print("Given Dictionary:", dict1)# new dictionary and# copying using copy() methoddict2 = dict1.copy()print("New copy:", dict2)# Updating dict2 elements and# checking the change in dict1dict2[10] = 10dict2[20][2] = '45' # list item updatedprint("Updated copy:", dict2) |
Output:
Given Dictionary: {10: 'a', 20: [1, 2, 3], 30: 'c'}
New copy: {10: 'a', 20: [1, 2, 3], 30: 'c'}
Updated copy: {10: 10, 20: [1, 2, '45'], 30: 'c'}How is it different from simple assignment “=”?
Unlike copy(), the assignment operator does deep copy.
Python3
# Python program to demonstrate difference# between = and copy()original = {1: 'geeks', 2: 'for'}# copying using copy() functionnew = original.copy()# removing all elements from new list# and printing bothnew.clear()print('new: ', new)print('original: ', original)original = {1: 'one', 2: 'two'}# copying using =new = original# removing all elements from new list# and printing bothnew.clear()print('new: ', new)print('original: ', original) |
Output:
new: {}
original: {1: 'geeks', 2: 'for'}
new: {}
original: {}

