python字典副本_如何复制字典并仅在Python中编辑副本?

python字典副本

Python never implicitly copies the dictionary or any objects. So, while we set dict2 = dict1, we're making them refer to the same dictionary object. Hence, even when we mutate the dictionary, all the references made to it, keep referring to the object in its current state.

Python绝不会隐式复制字典或任何对象。 因此,当我们设置dict2 = dict1时 ,我们使它们引用相同的字典对象。 因此,即使我们对字典进行了变异,对其的所有引用也会继续引用该对象的当前状态。

dict1 = {"key1": "abc", "key2": "efg"}

dict2 = dict1

print(dict1)
print(dict2)

dict2['key2'] = 'pqr'

print(dict1)
print(dict2)

Output

输出量

{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'pqr'}
{'key1': 'abc', 'key2': 'pqr'}

To copy a dictionary, either uses a shallow copy or deep copy approach, as explained in the below example.

复制字典 ,请使用浅层复制或深层复制方法 ,如以下示例中所述。

使用浅拷贝 (Using shallow copy)

dict1 = {"key1": "abc", "key2": "efg"}

print(dict1)

dict3 = dict1.copy()
print(dict3)

dict3['key2'] = 'xyz'

print(dict1)
print(dict3)

Output

输出量

{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'xyz'}

使用深度复制 (Using deep copy)

import copy

dict1 = {"key1": "abc", "key2": "efg"}

print(dict1)

dict4 = copy.deepcopy(dict1)
print(dict4)

dict4['key2'] = 'test1'

print(dict4)
print(dict1)

Output

输出量

{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'efg'}
{'key1': 'abc', 'key2': 'test1'}
{'key1': 'abc', 'key2': 'efg'}


翻译自: https://www.includehelp.com/python/how-to-copy-a-dictionary-and-only-edit-the-copy.aspx

python字典副本

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值