Python Dictionary copy method

Viewed 740

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?

2 Answers
Related