Why can reading an absent group change the keys in a defaultdict?

A subscript lookup on a missing key calls the default factory and stores its result. A get lookup skips the factory.

Python example and interpretation

A get lookup leaves an unseen label absent, while reading it with brackets creates an empty bucket. A later group count can include that empty label.

from collections import defaultdict
g=defaultdict(list)
before=g.get('x')
bucket=g['x']
[before,dict(g)]

Result [None, {'x': []}]

中文

为何读取缺失分组会改变 defaultdict 的键集合?

方括号读取缺失键会调用默认工厂并存入结果,而 get 查询不调用默认工厂。

Python 算例与适用条件

查询缺失标签前先用 get,字典仍为空;用下标取列表则建立空组。分组总数因而可能计入无样本组。

from collections import defaultdict
g=defaultdict(list)
before=g.get('x')
bucket=g['x']
[before,dict(g)]

结果 [None, {'x': []}]

References / 参考来源

Keep reading / 继续阅读