Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Dictionary copy method

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()

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

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.

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

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?

like image 867
sans0909 Avatar asked Oct 31 '22 07:10

sans0909


1 Answers

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.

like image 92
lciamp Avatar answered Nov 15 '22 03:11

lciamp