dict.get(key, default) evaluates default even if key exists

dn PythonList at DancesWithMice.info
Tue Dec 15 18:02:14 EST 2020


On 16/12/2020 07:52, Dan Stromberg wrote:
...> BTW, I tend to prefer collections.defaultdict over the two argument 
D.get
> or setdefault.


Contrarily, dict.get() seems 'better', unless (a) the dict's values are 
all to be initialised to the same value, eg all None, int 0, or empty 
list []; or (b) my fingers will be tired by the number of dict.get() 
calls to be typed.

This thought partly because it may be some 'distance' between the 
definition of the 'dict' as a defaultdict cf the built-in 'original', 
and therefore a simple boy (like me) finds it easy to forget or 'lose 
track'.

Also, because it is unusual to come-across a default-factory which 
initialises values to the defaultdict other than uniformly.

Have you seen any application of defaultdict with some more-complex and 
cleverly-designed default-factory function?

Other than personal-preference (which should be respected), and a 
uniform default-value, what is the rationale for defaultdict over 
dict.get()?
-- 
Regards =dn


More information about the Python-list mailing list