2 Comments

When using `dict()` to copy a dictionary is it a shallow copy or a deep copy?

Expand full comment
author

Good question. Yes, the default copying tends to be shallow copy since a data structure only contains references to the objects it contains, therefore, the natural way to make a copy of a data structure is to copy those references, which still point to the same original objects.

Here's confirmation:

>>> some_dict = {"first": [1, 2, 3], "second": [4, 5, 6]}

>>> another_dict = dict(some_dict)

>>> another_dict

{'first': [1, 2, 3], 'second': [4, 5, 6]}

>>> another_dict["first"].append(999)

>>> another_dict

{'first': [1, 2, 3, 999], 'second': [4, 5, 6]}

>>> some_dict

{'first': [1, 2, 3, 999], 'second': [4, 5, 6]}

Deep copy required more work! So you need to explicitly choose to use it!

Expand full comment