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

Python basic tutorial

Python flow control

Fonctions en Python

Types de données en Python

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python dictionary copy() usage and example

Python dictionary methods

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

The syntax of copy() is:

dict.copy()

copy() parameters

The 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 copying dictionaries using copy() and = operator

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

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

Example2: Use the = operator to copy the 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 the 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, the 'new' dictionary is cleared, but the 'original' dictionary remains unchanged.

Python dictionary methods