[issue42310] for loop creates element in defaultdict

Steven D'Aprano report at bugs.python.org
Tue Nov 10 09:04:59 EST 2020


Steven D'Aprano <steve+python at pearwood.info> added the comment:

As Larry said, yes, this is expected behaviour, and has nothing to do with the for loop. The purpose of defaultdict is that dict lookups create the entry if it doesn't exist:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> x = d['any key']
>>> d
defaultdict(<class 'list'>, {'any key': []})


So even though your code loops zero times, you have created a key 'a' with value [].

----------
nosy: +steven.daprano

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42310>
_______________________________________


More information about the Python-bugs-list mailing list