字典中的关键错误。如何让 Python 打印我的词典?

Key error in dictionary. How to make Python print my dictionary?

在我的作业中,这个问题要求我做一个函数,其中 Python 应该创建一个字典,其中有多少个单词在长字符串中以某个字母开头是对称的。对称意味着单词以一个字母开头并以同一个字母结尾。我不需要算法方面的帮助。我绝对知道我做对了,但是我只需要修复这个我无法弄清楚的关键错误。我写了d[word[0]] += 1,就是把以那个特定字母开头的单词出现的频率加1。

输出应如下所示(使用我在下面提供的字符串): {'d': 1, 'i': 3, 't': 1}

t = '''The sun did not shine
it was too wet to play
so we sat in the house
all that cold cold wet day

I sat there with Sally
we sat there we two
and I said how I wish
we had something to do'''

def symmetry(text):
    from collections import defaultdict
    d = {}
    wordList = text.split()
    for word in wordList:
        if word[0] == word[-1]:
            d[word[0]] += 1
    print(d)
print(symmetry(t))

您实际上从未使用过 collections.defaultdict,尽管您导入了它。将 d 初始化为 defaultdict(int),而不是 {},您就可以开始了。

def symmetry(text):
    from collections import defaultdict
    d = defaultdict(int)
    wordList = text.split()
    for word in wordList:
        if word[0] == word[-1]:
            d[word[0]] += 1
    print(d)

print(symmetry(t))

结果:

defaultdict(<class 'int'>, {'I': 3, 't': 1, 'd': 1})

您正试图增加尚未完成的条目的值,导致 KeyError。当还没有密钥条目时,您可以使用 get();默认值为 0 或您选择的任何其他值 )。使用此方法,您将不需要 defaultdict尽管在某些情况下非常有用)。

def symmetry(text):
    d = {}
    wordList = text.split()
    for word in wordList:
        key = word[0]
        if key == word[-1]:
            d[key] = d.get(key, 0) + 1
    print(d)
print(symmetry(t))

示例输出

{'I': 3, 'd': 1, 't': 1}