深度阅读

How to copy a dictionary in Python?

作者
作者
2023年08月22日
更新时间
22.24 分钟
阅读时间
0
阅读量

In Python, you can use the copy() method or the dict() constructor to make a copy of an existing dictionary. However, there are some differences in how these strategies make copies of the dictionary. Here are some examples:

Using the copy() method:

original_dict = {1: 'one', 2: 'two', 3: 'three'}
new_dict = original_dict.copy()

# Make a change in original_dict
original_dict[1] = 'ONE'

print('original_dict:', original_dict)
print('new_dict:', new_dict)

In this example, the copy() method is used to create a new dictionary that is a shallow copy of the original_dict. This means that new dictionary contains references to the same objects as the original dictionary, rather than new copies of those objects. If any of the referenced objects are mutable, changes to those objects in the original dictionary will also be reflected in the new dictionary.

Using the dict() constructor:

original_dict = {1: 'one', 2: 'two', 3: 'three'}
new_dict = dict(original_dict)

# Make a change in original_dict
original_dict[1] = 'ONE'

print('original_dict:', original_dict)
print('new_dict:', new_dict)

In this example, the dict() constructor is used to create a new dictionary that is also a shallow copy of the original_dict. As with the copy() method, the new dictionary contains references to the same objects as the original dictionary.

If you need a deep copy of the dictionary – that is, a copy where all objects are themselves copied rather than referenced – you can use the copy module’s deepcopy() function. Here’s an example:

import copy

original_dict = {1: ['one', 'two'], 2: ['three', 'four'], 3: ['five', 'six']}
new_dict = copy.deepcopy(original_dict)

# Make a change in original_dict
original_dict[1][0] = 'ONE'

print('original_dict:', original_dict)
print('new_dict:', new_dict)

In this example, the deepcopy() function is used to create a new dictionary that is a deep copy of the original_dict. This means that all objects in the new dictionary are copied recursively, rather than just having references to the same objects as the original dictionary. Consequently, changes made to mutable objects in the original dictionary do not affect

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。