如何复制字典并仅在Python中编辑副本?
Python绝不会隐式复制字典或任何对象。因此,当我们设置dict2=dict1时,我们使它们引用相同的字典对象。因此,即使我们对字典进行了变异,对其的所有引用也会继续引用该对象的当前状态。
dict1 = {"key1": "abc", "key2": "efg"}
dict2 = dict1
print(dict1)
print(dict2)
dict2['key2'] = 'pqr'
print(dict1)
print(dict2)输出结果
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'pqr'}
{'key1': 'abc', 'key2': 'pqr'}要复制字典,请使用浅拷贝或深拷贝方法,如以下示例中所述。
使用浅拷贝
dict1 = {"key1": "abc", "key2": "efg"}
print(dict1)
dict3 = dict1.copy()
print(dict3)
dict3['key2'] = 'xyz'
print(dict1)
print(dict3)输出结果
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'xyz'}使用深度复制
import copy
dict1 = {"key1": "abc", "key2": "efg"}
print(dict1)
dict4 = copy.deepcopy(dict1)
print(dict4)
dict4['key2'] = 'test1'
print(dict4)
print(dict1)输出结果
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'test1'}
{'key1': 'abc', 'key2': 'efg'}热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练