我已经阅读了python文档中的示例,但仍然不明白这个方法是什么意思。有人能帮帮我吗?下面是python文档中的两个例子

>>> from collections import defaultdict

>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]

and

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

参数int和list是干什么用的?


当前回答

这里有一个关于defaultdicts的很好的解释:http://ludovf.net/blog/python-collections-defaultdict/

基本上,参数int和list是传递的函数。记住,Python接受函数名作为参数。Int默认返回0,而list在使用括号调用时返回空列表。

在正常的字典中,如果在你的例子中我尝试调用d[a],我会得到一个错误(KeyError),因为只有键m, s, I和p存在,键a还没有初始化。但在defaultdict中,它接受函数名作为参数,当您尝试使用未初始化的键时,它只是调用您传入的函数并将其返回值分配为新键的值。

其他回答

在以下情况下,defaultdict也会引发keyerror:

from collections import defaultdict
d = defaultdict()
print(d[3]) #raises keyerror

总是记得给defaultdict参数

d = defaultdict(int)

文档和解释几乎是不言自明的:

http://docs.python.org/library/collections.html#collections.defaultdict

类型函数(int/str等)作为参数传递,用于初始化dict中没有的任何给定键的默认值。

Usually, a Python dictionary throws a KeyError if you try to get an item with a key that is not currently in the dictionary. The defaultdict in contrast will simply create any items that you try to access (provided of course they do not exist yet). To create such a "default" item, it calls the function object that you pass to the constructor (more precisely, it's an arbitrary "callable" object, which includes function and type objects). For the first example, default items are created using int(), which will return the integer object 0. For the second example, default items are created using list(), which returns a new empty list object.

defaultdict意味着如果在字典中没有找到一个键,那么不会抛出KeyError,而是创建一个新条目。这个新条目的类型由defaultdict的参数给出。

例如:

somedict = {}
print(somedict[3]) # KeyError

someddict = defaultdict(int)
print(someddict[3]) # print int(), thus 0
#dictinary and defaultdict

normaldictionary=dict()
print(type(normaldictionary))
#print(normaldictionary["keynotexisit"])
#Above normal dictionary give an error as key not present

from collections import defaultdict
defaultdict1=defaultdict()
print(type(defaultdict1))
#print(defaultdict1['keynotexisit'])
######################################

from collections import defaultdict
default2=defaultdict(int)
print(default2['keynotexist'])

https://msatutorpy.medium.com/different-between-dictionary-and-defaultdictionary-cb215f682971