charany1
charany1

Reputation: 911

Python3 : Do dict constructor create deep copies?

I'm trying to understand shallow-copy vs deep-copy concept in Python3.

From below code I found that change done in dict2 is not getting reflected back in dict1.

1>>> dict1 = {1:[1,2]}
2>>> dict2 = dict(dict1)
3>>> dict2[1]=[1,2,3]
4>>> dict1,dict2
({1: [1, 2]}, {1: [1, 2, 3]})

Am I correct in understanding that a deep copy is created on line#2 in above code.

Upvotes: 2

Views: 443

Answers (1)

Adam.Er8
Adam.Er8

Reputation: 13403

The dict "constructor" can accept a "mapping object", in which case it creates a new dictionary initialized from a mapping object's (key, value) pairs.

This is what happens here, as dict1 is a mapping object.

This is however NOT a deep copy, take a look at this example:

>>> dict1 = {1:[1,2]}
>>> dict2 = dict(dict1)
>>> dict1,dict2
({1: [1, 2]}, {1: [1, 2]})
>>> dict1[1].append(4)
>>> dict1,dict2
({1: [1, 2, 4]}, {1: [1, 2, 4]})
>>>

you see how both dict1 and dict2 changed even though I changed just dict1? that's because they both point to the same list.

In your example, you replaced dict2's list with a new list, and what this demonstrates is the new dict is indeed a copy and not just a ref to the original dict.

To put it simply: the dictionary itself is "copied", but the inner values held in it are not.

Upvotes: 5

Related Questions