Python - Copy Dictionaries



Copy Dictionaries Using copy()

Dictionaries cannot be copied directly by using the assignment operator (=), you can use the copy() method to create a shallow copy of a dictionary.

Example: Copy Dictionaries Using copy() Method

The following example demonstrates the creation of a shallow copy of a dictionary using the copy() method.

# Creating a dictionary
dict1 = {"name": "Krishna", "age": "27", "doy": 1992}

# Copying the dictionary
dict2 = dict1.copy()

# Printing both of the dictionaries
print("dict1 :", dict1)
print("dict2 :", dict2)

It will produce the following output

dict1 : {'name': 'Krishna', 'age': '27', 'doy': 1992}
dict2 : {'name': 'Krishna', 'age': '27', 'doy': 1992}

Copy Dictionaries Using dict()

You can also copy the dictionaries using the dict() method which is a built-in method in Python. It actually creates a new dictionary using the contents of an existing dictionary.

Example: Copy Dictionaries Using dict() Method

The following example demonstrates the creation of a copy of a dictionary using the dict() method.

# Creating a dictionary
dict1 = {"name": "Krishna", "age": "27", "doy": 1992}

# Copying the dictionary
dict2 = dict(dict1)

# Printing both of the dictionaries
print("dict1 :", dict1)
print("dict2 :", dict2)

It will produce the following output

dict1 : {'name': 'Krishna', 'age': '27', 'doy': 1992}
dict2 : {'name': 'Krishna', 'age': '27', 'doy': 1992}
Advertisements