Python 检查defaultdict中的密钥

Python 检查defaultdict中的密钥,python,dictionary,Python,Dictionary,我有一段代码,它应该通过python中的键运行defaultdict,如果该键不在defaultdict中,它就会被添加 我遇到了一个常规定义词典没有遇到的错误,我在解决它时遇到了一些困难: 守则: from collections import defaultdict def counts(line): for word in line.split(): if word not in defaultdict.keys(): word = "".

我有一段代码,它应该通过python中的键运行
defaultdict
,如果该键不在
defaultdict
中,它就会被添加

我遇到了一个常规定义词典没有遇到的错误,我在解决它时遇到了一些困难:

守则:

from collections import defaultdict

def counts(line):
    for word in line.split():
        if word not in defaultdict.keys():
            word = "".join(c for c in word if c not in ('!', '.', ':', ','))
            defaultdict[word] = 0
        if word != "--":
            defaultdict[word] += 1
错误:

如果单词不在defaultdict.keys()中:
TypeError:“dict”对象的描述符“key”需要参数

此处没有构造
defaultdict
对象,您只需引用
defaultdict
类即可

您可以创建一个,如:

from collections import defaultdict

def counts(line):
    dd = defaultdict(int)
    for word in line.split():
        word = ''.join(c for c in word if c not in ('!', '.', ':', ','))
        if word not in dd:
            dd[word] = 0
        if word != '--':
            dd[word] += 1
    return dd

defaultdict
是一个类;您需要一个对象:

from collections import defaultdict

def counts(line, my_dict):
    for word in line.split():
        if word not in my_dict.keys():
            word = "".join(c for c in word if c not in ('!', '.', ':', ','))
            my_dict[word] = 0 
        if word != "--":
            my_dict[word] += 1


my_dict = defaultdict()

counts("Now is the time for all good parties to come to the aid of man.", my_dict)
print(my_dict)
输出:

defaultdict(None, {'Now': 1, 'is': 1, 'the': 2, 'time': 1, 'for': 1, 'all': 1, 'good': 1, 'parties': 1, 'to': 2, 'come': 1, 'aid': 1, 'of': 1, 'man': 1})

defaultdict
是这里的一个类,而不是
defaultdict
实例。@WillemVanOnsem哦,我明白了,谢谢。在python中创建defaultdict实例的语法是什么?此外,您可以在某些dict:中使用if-word检查实例键。
defaultdict(None, {'Now': 1, 'is': 1, 'the': 2, 'time': 1, 'for': 1, 'all': 1, 'good': 1, 'parties': 1, 'to': 2, 'come': 1, 'aid': 1, 'of': 1, 'man': 1})