从集合中导入 defaultdict

from collections import defaultdict

为什么我没有将defaultdict默认值设置为零(int),我的以下程序没有给我结果:

>>> doc
'A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart. I am alone, and feel the charm of existence in this spot, which was created for the bliss of souls like mine. I am so happy'
>>> some = defaultdict()
>>> for i in doc.split():
...  some[i] = some[i]+1
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyError: 'A'
>>> some
defaultdict(None, {})
>>> i
'A'

但它适用于默认值

>>> some = defaultdict(int)
>>> for i in doc.split():
...  some[i] = some[i]+1
...
>>> some
defaultdict(<class 'int'>, {'A': 1, 'wonderful': 1, 'serenity': 1, 'has': 1, 'taken': 1, 'possession': 1, 'of': 4, 'my': 2, 'entire': 1, 'soul,': 1, 'like': 2, 'these': 1, 'sweet': 1, 'mornings': 1, 'spring': 1, 'which': 2, 'I': 3, 'enjoy': 1, 'with': 1, 'whole': 1, 'heart.': 1, 'am': 2, 'alone,': 1, 'and': 1, 'feel': 1, 'the': 2, 'charm': 1, 'existence': 1, 'in': 1, 'this': 1, 'spot,': 1, 'was': 1, 'created': 1, 'for': 1, 'bliss': 1, 'souls': 1, 'mine.': 1, 'so': 1, 'happy': 1})
>>>

你能说说为什么会这样吗?

如文档所述:

The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

因此,如果你只写defaultdict而不向构造函数传递任何值,则默认值设置为None 查看输出:

some = defaultdict()
print(some)    # defaultdict(None, {}) 

并且当值设置为None时,不能执行:some[i] = some[i]+1.
因此,您必须将默认值显式设置为 intsome = defaultdict(int)