2

According to the official docs the dictionary copy is shallow, i.e. it returns a new dictionary that contains the same key-value pairs:

dict1 = {1: "a", 2: "b", 3: "c"}

dict1_alias = dict1
dict1_shallow_copy = dict1.copy()

My understanding is that if we del an element of dict1 both dict1_alias & dict1_shallow_copy should be affected; however, a deepcopy would not.

del dict1[2]
print(dict1)
>>> {1: 'a', 3: 'c'}  
print(dict1_alias)
>>> {1: 'a', 3: 'c'} 

But dict1_shallow_copy 2nd element is still there!

print(dict1_shallow_copy)
>>>  {1: 'a', 2: 'b', 3: 'c'}  

What am I missing?

boardtc
  • 1,304
  • 1
  • 15
  • 20
  • 3
    Even a shallow copy is still a **copy**, not the same object. – khelwood Mar 26 '19 at 23:49
  • 1
    "Now if we del an element of dict1 both dict1_alias & dict1_shallow_copy should be affected." No, absolutely not. They are *different dict objects*, that is why they are *copies*. – juanpa.arrivillaga Mar 27 '19 at 02:31

1 Answers1

3

A shallow copy means that the elements themselves are the same, just not the dictionary itself.

>>> a = {'a':[1, 2, 3],  #create a list instance at a['a']
         'b':4,
         'c':'efd'}
>>> b = a.copy()         #shallow copy a
>>> b['a'].append(2)     #change b['a']
>>> b['a']
[1, 2, 3, 2]
>>> a['a']               #a['a'] changes too, it refers to the same list
[1, 2, 3, 2]             
>>> del b['b']           #here we do not change b['b'], we change b
>>> b
{'a': [1, 2, 3, 2], 'c': 'efd'}
>>> a                    #so a remains unchanged
{'a': [1, 2, 3, 2], 'b': 4, 'c': 'efd'}1
Artemis
  • 2,553
  • 7
  • 21
  • 36