Assume we have a simple Python dictionary:
dict_ = {'foo': 1, 'bar': 2}
Which is the better way to copy this dictionary?
copy1 = dict(dict_)
copy2 = dict_.copy()
Is there a compelling reason to favour one approach over the other?
Python Dictionary copy() The dict. copy() method returns a shallow copy of the dictionary. The dictionary can also be copied using the = operator, which points to the same object as the original. So if any change is made in the copied dictionary will also reflect in the original dictionary.
Shallow copies of dictionaries can be made using dict.copy() , and of lists by assigning a slice of the entire list, for example, copied_list = original_list[:] .
The copy. copy() function creates shallow copies of objects.
Using built-in method list() to copy list. Another way to copy a list in Python is to use the built-in method list(). It also creates a shallow copy which means any time a modification is made in the new list, it will not show on the old list.
I always use the dict
constructor: it makes it obvious that you are creating a new dict
whereas calling the copy
method on an object could be copying anything. Similarly for list
I prefer calling the constructor over copying by slicing.
Note that if you use subclasses of dict
using the copy
method can get confusing:
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> d['a']
0
>>> d.copy()
defaultdict(<class 'int'>, {'a': 0})
>>> dict(d)
{'a': 0}
>>>
The copy
method of defaultdict
gives you another defaultdict
, but unless you override copy
in a subclass the default action is just to give you a dict
:
>>> class MyDict(dict): pass
>>> d = MyDict(a=1)
>>> d
{'a': 1}
>>> type(d)
<class '__main__.MyDict'>
>>> type(d.copy())
<class 'dict'>
That means you have to know about the internal details of a subclass to know what type the copy
method will return.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With