English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operation

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Python dictionary copy() usage and example

Python dictionary methods

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

The syntax of copy() is:

dict.copy()

copy() parameters

copy() method has no parameters.

From the copy() return value

This method returns a shallow copy of the dictionary. It does not modify the original dictionary.

Example1: How does copying affect dictionaries?

original = {1: 'one', 2: 'two'}
new = original.copy()
print('Original dictionary: ', original)
print('Copy dictionary: ', new)

When running the program, the output is:

Original dictionary: {1: 'one', 2: 'two'}
Copy dictionary: {1: 'one', 2: 'two'}

The difference between using copy() method and = operator to copy a dictionary

When using the copy() method, a new dictionary will be created, which will fill with the copy of the references in the original dictionary.

When using the = operator, a new reference to the original dictionary will be created.

Example2: Use = operator to copy a dictionary

original = {1: 'one', 2: 'two'}
new = original
# Delete all elements from the list
new.clear()
print('new: ', new)
print('original: ', original)

When running the program, the output is:

new: {}
original: {

Here, when the new dictionary is cleared, the original dictionary is also cleared.

Example3: Use copy() to copy a dictionary

original = {1: 'one', 2: 'two'}
new = original.copy()
# Delete all elements from the list
new.clear()
print('new: ', new)
print('original: ', original)

When running the program, the output is:

new: {}
original: {1: 'one', 2: 'two'}

Here, after the new dictionary is cleared, the original dictionary remains unchanged.

Python dictionary methods