This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: for loop creates element in defaultdict
Type: Stage: resolved
Components: Versions: Python 3.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: sandrobarna, steven.daprano
Priority: normal Keywords:

Created on 2020-11-10 13:39 by sandrobarna, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg380661 - (view) Author: Sandro Barnabishvili (sandrobarna) Date: 2020-11-10 13:39
from collections import defaultdict
d = defaultdict(list)
for _ in d['a']: pass
print(d.keys())

For loop creates element with key 'a'. Is it expected behavior?
msg380662 - (view) Author: Larry Hastings (larry) * (Python committer) Date: 2020-11-10 13:43
Yes.  Read the documentation for "defaultdict".

In the future, please read the documentation before filing bugs.
msg380670 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2020-11-10 14:04
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 [].
History
Date User Action Args
2022-04-11 14:59:37adminsetgithub: 86476
2020-11-10 14:06:06larrysetnosy: - larry
2020-11-10 14:04:59steven.dapranosetnosy: + steven.daprano
messages: + msg380670
2020-11-10 13:43:09larrysetstatus: open -> closed

components: - Argument Clinic
type: behavior ->
nosy: larry, sandrobarna
messages: + msg380662
resolution: not a bug
stage: resolved
2020-11-10 13:39:42sandrobarnacreate