The copy() function in python helps to make a copy of the dictionary. We can say that it returns a shallow copy which means any changes in the new dictionary won't reflect the original one.
dict.copy()
The copy() method doesn't take any parameters.
Sometimes we use the =operator to copy the dictionary the difference is that the =operator creates the reference to the dictionary and copy() creates a new dictionary.
Input | Return Value |
---|---|
dictionary | dictionary copy |
originaldict = {5:'five', 6:'six'}
newdict = originaldict.copy()
print('Orignal: ', originaldict)
print('New: ', newdict)
Output:
Orignal: {5: 'five', 6: 'six'} New: {5: 'five', 6: 'six'}
originaldict = {5:'five', 6:'six'}
newdict = originaldict
# removing all elements from the list
newdict.clear()
print('New: ', newdict)
print('Original: ', originaldict)
Output:
New: {} Original: {}
originaldict = {5:'five', 6:'six'}
newdict = originaldict.copy()
# removing all elements from the list
newdict.clear()
print('New: ', newdict)
print('Original: ', originaldict)
Output:
New: {} Original: {5: 'five', 6: 'six'}