Python Dictionary - Copy Method

Method Name:

copy

Method Signature:

copy()

Parameters:

none

Return Value:

A dictionary containing same object references as the source dictionary.

Method Overview:

Returns a shallow copy of the python dictionary object.

Shallow copying of Python dict objects

Example:

# Example Python program that does
# a shallow copy of a dictionary instance

# Define a Point class with x,y attributes
class Point:
    # Initialization of the object
    def __init__(self, x, y):
        self.x     = x;
        self.y = y;

    # String representation of the object    
    def __str__(self):        
        return "%d,%d"%(self.x, self.y)

# Create a dictionary
nameValues = dict();

# Populate the dictionary with instances of A
for i in range(0, 5):
    pt = Point(i, i*2);
    nameValues[i]=pt;

print("Address of the dictionary:");
print(hex(id(nameValues)));

# Print the object references contained in the dictionary
print("Address of dictionary elements:");
print(nameValues);

# Print the actual dictionary elements
print("Contents of the dictionary");
for item in nameValues:
    print("%d: Point(%s)"%(item, nameValues[item]));

# Do a shallow copy of the dictionary
nameValuesCopy = nameValues.copy();

print("Address of the new dictionary:");
print(hex(id(nameValuesCopy)));

print("Address of the elements in the new dictionary:");
print(nameValuesCopy);

# Print the elements from the new dictionary
print("Contents of the new dictionary");
for item in nameValuesCopy:
    print("%d: Point(%s)"%(item, nameValuesCopy[item]));

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)

Copyright 2023 © pythontic.com