Python Dictionary Copy Method

I have a question with a way to copy a dictionary for example, let's say I have

>> d = {'pears': 200, 'apples': 400, 'oranges': 500, 'bananas': 300} >> copy_dict = d.copy() 

Now, if I check the id of both d and copy_dict, both of them are different

 >> id(d) o/p = 140634603873176 >> id(copy_dict) o/p = 140634603821328 

but if I check the identifier of objects in dictionaries, then they have the 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.

Now, if I change the value of the pear key to d, there are no changes in copy_dict in the same way, and when I check the identifier, id (d ['pears'])! = Id (copy_dict ['pears'])

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

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

Could you give me a full description of the differences between a deep copy and a shallow copy?

+5
source share
2 answers

by changing the value, you change what the key points to. Changing the value in the original dictionary will not change what the key in the copy indicates.

A shallow copy creates a new compound object, and then (as far as possible) inserts links to objects found in the original.

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

When you copy something, it copies the original values ​​of the object that it copies, but creates a new object. It does not reflect the original object.

+2
source

The reason is because you performed an assignment operation that replaces the values, and not a value change operation.

 copy_dict = d.copy() 

Called a new dict to create and its keys / values ​​were initialized from d . You noted an important point - these are separate objects with different identifiers that simply refer to the same keys and values.

 d['pears'] = 700 

removed the link to 200 from d['pears'] and added the link to 700 . This reassignment was done on object d , so it wouldn’t naturally have been seen by other dicts that were simply initialized with the same keys and values.

In contrast, suggested that you simply assigned the original dict to a second variable

 copy_dict = d 

Here, since both d and copy_dict refer to the same dict , reassignment to this dict will be visible to both variables, since they refer to the same object.

0
source

Source: https://habr.com/ru/post/1244789/


All Articles