Easy Tutorial
❮ Ref Set Difference Python Att Dictionary Fromkeys ❯

Python3 Dictionary copy() Method

Python3 Dictionary


Description

The Python dictionary copy() function returns a shallow copy of the dictionary.

Syntax

The syntax for the copy() method is:

dict.copy()

Parameters

Return Value

Returns a shallow copy of the dictionary.

Example

The following example demonstrates the use of the copy() function:

#!/usr/bin/python3

dict1 = {'Name': 'tutorialpro', 'Age': 7, 'Class': 'First'}

dict2 = dict1.copy()
print("New copied dictionary is : ", dict2)

The output of the above example is:

New copied dictionary is :  {'Age': 7, 'Name': 'tutorialpro', 'Class': 'First'}

Difference Between Direct Assignment and Copy

This can be illustrated with the following example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

dict1 = {'user': 'tutorialpro', 'num': [1, 2, 3]}

dict2 = dict1          # Shallow copy: reference object
dict3 = dict1.copy()   # Shallow copy: deep copy parent object (first level), child objects (second level) are not copied, they are references

# Modify data
dict1['user'] = 'root'
dict1['num'].remove(1)

# Output results
print(dict1)
print(dict2)
print(dict3)

In the example, dict2 is actually a reference (alias) of dict1, so the output is consistent. dict3's parent object is deeply copied and will not change with modifications to dict1, while the child object is shallow copied and will change with modifications to dict1.

{'user': 'root', 'num': [2, 3]}
{'user': 'root', 'num': [2, 3]}
{'user': 'tutorialpro', 'num': [2, 3]}

Knowledge Expansion

Python Direct Assignment, Shallow Copy, and Deep Copy Explained


Python3 Dictionary

❮ Ref Set Difference Python Att Dictionary Fromkeys ❯