Python字典复制方法 [英] Python Dictionary copy method

查看:95
本文介绍了Python字典复制方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对字典复制方法有疑问 例如,假设我有

I have question with dictionary copy method for example lets say i have

>> d = {'pears': 200, 'apples': 400, 'oranges': 500, 'bananas': 300}

>> copy_dict = d.copy()

现在,如果我同时检查d和copy_dict的ID,两者都是不同的

Now if I check id's of both d and copy_dict, both are different

>> id(d)
o/p = 140634603873176

>> id(copy_dict)
o/p = 140634603821328

但是如果我检查字典中对象的ID,它们的含义相同,即id(d ['pears'])= id(copy_dict ['pears'])

but if I check the id of objects in the dictionaries they are same meaning id(d['pears']) = id(copy_dict['pears'])

>> id(d['pears'])
o/p = 140634603971648
>> id (copy_dict['pears'])
o/p = 140634603971648

新字典中的所有对象都是对与原始字典相同的对象的引用.

All objects in the new dict are references to the same objects as the original dict.

现在,如果我更改d中键"pears"的值,则copy_dict中的相同键没有变化,当我现在检查ID时, id(d ['pears'])!= id(copy_dict ['pears'])

Now if I change the value of key 'pears' in d, there is no change in same key in copy_dict and when I check the id's now, id(d['pears']) != id(copy_dict['pears'])

>> d['pears'] = 700
>> print copy_dict['pears']
o/p = 200

我的问题是,如果新字典中的对象引用的对象与原始字典中的对象相同,那么当原始字典中的值更改时,为什么新字典的值没有更改,Python如何立即更改看到值更改就立即获得ID?

My question is if the objects in the new dict are references to the same objects as the original dict why is the value of the new dict did not change when the value in the original dictionary got changed and how did Python immediately change the id's as soon as it saw the value changed?

能否请您完整介绍一下深拷贝和浅拷贝之间的区别?

Can you please give me full description of difference between deep and shallow copy?

推荐答案

通过更改值,您正在更改键所指向的内容.更改原始词典中的值不会更改副本中的键所指向的内容.

by changing the value, you are changing what the key is pointing at. Changing the value in the original dictionary isn't going to change what the key in the copy is pointing to.

浅表副本会构造一个新的复合对象,然后(到 在可能的范围内)将引用插入其中的对象 原本的.

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

深层副本会构造一个新的复合对象,然后, 递归地将在其中找到的对象的副本插入其中 原始的.

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

当您复制某些内容时,它会复制它正在复制的对象的原始值,但是会创建一个新的对象.它不会镜像原始对象.

When you copy something it copies the original values of the object it is copying, but it creates a new object. It doesn't mirror the original object.

这篇关于Python字典复制方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆