Python Dictionary copy()

The dict.copy() method returns a shallow copy of the dictionary.

The dictionary can also be copied using the = operator, which points to the same object as the original. So if any change is made in the copied dictionary will also reflect in the original dictionary.

Syntax:

dict.copy()

Parameters:

No parameters.

Return type:

Returns a shallow copy of the dictionary.

The following example demonstrates the dict.copy() method.

Example:
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
newRomanNums = romanNums.copy()
print("Original dictionary: ",romanNums)
print("Copied dictionary: ",newRomanNums)
Output
Original dictionary:  {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5}
Copied dictionary:  {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5}

When a dictionary is copied through the copy() method, any change made in a new dictionary will not be reflected in the original dictionary.

Example:
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
newRomanNums = romanNums.copy()
del newRomanNums['V'] # deleting 'V'
print("Original dictionary: ",romanNums)
print("Copied dictionary: ",newRomanNums)
Output
Original dictionary:  {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5}
Copied dictionary:  {'I': 1, 'II': 2, 'III': 3, 'IV': 4}

When a = operator is used to copy a dictionary, any change in the copied one will be reflected in the original dictionary and vice-versa.

Example:
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
newRomanNums = romanNums
newRomanNums.clear()
print("Original dictionary: ",romanNums)
print("Copied dictionary: ",newRomanNums)
Output
Original dictionary:  {}
Copied dictionary:  {}
Want to check how much you know Python?