Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to make a shallow copy of a Python dictionary?

Tags:

python

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?

like image 679
davidchambers Avatar asked Jan 03 '11 09:01

davidchambers


People also ask

What is the correct way to copy a dictionary in Python?

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.

What is the name of function to make a shallow copy of 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[:] .

How do you shallow copy an object in Python?

The copy. copy() function creates shallow copies of objects.

Does list () create a shallow copy?

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.


1 Answers

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.

like image 188
Duncan Avatar answered Sep 20 '22 23:09

Duncan