博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python字典副本_如何复制字典并仅在Python中编辑副本?
阅读量:2528 次
发布时间:2019-05-11

本文共 1356 字,大约阅读时间需要 4 分钟。

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 = dict1print(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 , 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 copydict1 = {
"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'}

翻译自:

python字典副本

转载地址:http://hdtzd.baihongyu.com/

你可能感兴趣的文章
Thrift源码分析(二)-- 协议和编解码
查看>>
考勤系统之计算工作小时数
查看>>
4.1 分解条件式
查看>>
Equivalent Strings
查看>>
flume handler
查看>>
收藏其他博客园主写的代码,学习加自用。先表示感谢!!!
查看>>
H5 表单标签
查看>>
su 与 su - 区别
查看>>
C语言编程-9_4 字符统计
查看>>
在webconfig中写好连接后,在程序中如何调用?
查看>>
限制用户不能删除SharePoint列表中的条目(项目)
查看>>
【Linux网络编程】使用GDB调试程序
查看>>
feign调用spring clound eureka 注册中心服务
查看>>
ZT:Linux上安装JDK,最准确
查看>>
LimeJS指南3
查看>>
关于C++ const成员的一些细节
查看>>
《代码大全》学习摘要(五)软件构建中的设计(下)
查看>>
C#检测驱动是否安装的问题
查看>>
web-4. 装饰页面的图像
查看>>
微信测试账户
查看>>