Python Dictionary copy() method
Python Dictionary copy() method
The dictionary.copy () method in Python returns a copy of the specified dictionary.
Syntax
dictionary.copy ()
Parameter
NA
Return
None
Example 1
# Python program explaining # the dictionary.copy() method # initialising the dictionary fruits = { "banana": "apple", "orange": "mango", "grapes": 5 } # printing the dictionary print("Dictionary:",fruits) # copying the dictionary elements. dictionary2= fruits.copy() print("After the copying the dictionary...") print("Dictionary2:",fruits)
Output
Dictionary: {'grapes': 5, 'orange': 'mango', 'banana': 'apple'} After the copying the dictionary... Dictionary2: {'grapes': 5, 'orange': 'mango', 'banana': 'apple'}
Example 2
# Python program explaining # the dictionary.copy() method #initializing the dictionary dictionary = {1: "numbers", 2: "digits"} # copying the elements of dictionary in dictionary1 dictionary1 = dictionary.copy() print('dictionary: ', dictionary) print("After copying the dictionary elements in dictionary1...") print('dictionary1: ', dictionary1)
Output
dictionary: {1: 'numbers', 2: 'digits'} After copying the dictionary elements in dictionary1... dictionary1: {1: 'numbers', 2: 'digits'}
Example 3
# Python program explaining # the dictionary.copy() method dictionary = {1:'one', 2:'two',3:'three'} # copying the original dictionary using copy() function copyElement = dictionary.copy() # removing all elements from the dictionary # Only new dictionary becomes empty as copy() # does shallow copy. copyElement.clear() # printing the dictionary after clearing all elements print('new: ', copyElement) # printing the original elements print('original: ', dictionary)
Output
new: {} original: {1: 'one', 2: 'two', 3: 'three'}