I always use the dict constructor: it makes it obvious that you are creating a new dict , while calling the copy method of an object can copy anything. Similarly, for list I prefer to call the constructor over copy by slicing.
Note that if you use dict subclasses with the copy method, you may be confused:
>>> from collections import defaultdict >>> d = defaultdict(int) >>> d['a'] 0 >>> d.copy() defaultdict(<class 'int'>, {'a': 0}) >>> dict(d) {'a': 0} >>>
The copy defaultdict method provides you with another defaultdict , but if you do not override copy in a subclass, the default action is simply to specify a dict :
>>> class MyDict(dict): pass >>> d = MyDict(a=1) >>> d {'a': 1} >>> type(d) <class '__main__.MyDict'> >>> type(d.copy()) <class 'dict'>
This means that you need to know about the inner details of the subclass to find out what type the copy method returns.
Duncan
source share