davidchambers davidchambers - 9 months ago 24
Python Question

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

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?


One could favor option #1 (dict(dict_)) because of the principle of least surprise: you can do the same for lists: list(list_), and lists don't have a copy() method.

That said, many good points were raised in the answers. This indicates that there might not be any obviously better solution, and that both are fine, as long as you do what you intend to do (the point about subclassing dict might be crucial, in some codes, for instance). So, I would just choose whatever feels right for your application given the points raised in the responses!