Method Name:
copy
Method Signature:
copy()
Parameters:
none
Return Value:
A dictionary containing same object references as the source dictionary.
Method Overview:
-
The copy() method of the Python dictionary class creates a new dictionary object and copies the references of the elements from the old dictionary to the new dictionary. The new dictionary object is returned.
-
The new dictionary does not recreate its elements. It does a shallow copy of the elements from the old dictionary to the new dictionary. The Python example below returns new object which has an object reference 0x7fac39221440. The elements of the new dictionary are the same object references - 0x7fac3922bfd0, 0x7fac3922bf10 and so on.
- After doing a shallow copy, if the references/values against the keys in one dictionary is updated, the element in the other dictionary will get updated - as they are shallow copies or just the same references. This behaviour works when the values against the keys are class objects, because class objects can be updated. For values of basic types only assignment is possible. Hence during the assignment a new value/object of basic type - for example, an integer is created and replaced for a specific key.
Example:
# Example Python program that does # Define a Point class with x,y attributes # String representation of the object # Create a dictionary # Populate the dictionary with instances of A print("Address of the dictionary:") # Print the object references contained in the dictionary # Print the actual dictionary elements # Do a shallow copy of the dictionary print("Address of the new dictionary:") print("Address of the elements in the new dictionary:") # Print the elements from the new dictionary |
Output:
Address of the dictionary: 0x7fac39221d00 Address of dictionary elements: {0: <__main__.Point object at 0x7fac3922bfd0>, 1: <__main__.Point object at 0x7fac3922bf10>, 2: <__main__.Point object at 0x7fac3922be50>, 3: <__main__.Point object at 0x7fac3922bdf0>, 4: <__main__.Point object at 0x7fac3922bd90>} Contents of the dictionary 0: Point(0,0) 1: Point(1,2) 2: Point(2,4) 3: Point(3,6) 4: Point(4,8) Address of the new dictionary: 0x7fac39221440 Address of the elements in the new dictionary: {0: <__main__.Point object at 0x7fac3922bfd0>, 1: <__main__.Point object at 0x7fac3922bf10>, 2: <__main__.Point object at 0x7fac3922be50>, 3: <__main__.Point object at 0x7fac3922bdf0>, 4: <__main__.Point object at 0x7fac3922bd90>} Contents of the new dictionary 0: Point(0,0) 1: Point(1,2) 2: Point(2,4) 3: Point(3,6) 4: Point(4,8) |