[英]Key error in dictionary. How to make Python print my dictionary?
In my homework, this question is asking me to make a function where Python should create dictionary of how many words that start with a certain letter in the long string is symmetrical. 在我的作业中,这个问题要我做一个函数,Python应该在该函数中创建字典,该字典中长字符串中以某个字母开头的单词是对称的。 Symmetrical means the word starts with one letter and ends in the same letter.
对称是指单词以一个字母开头,以一个字母结尾。 I do not need help with the algorithm for this.
我不需要与此算法有关的帮助。 I definitely know I have it right, but however I just need to fix this Key error that I cannot figure out.
我当然知道我做对了,但是但是我只需要修复无法解决的Key错误。 I wrote
d[word[0]] += 1
, which is to add 1 to the frequency of words that start with that particular letter. 我写了
d[word[0]] += 1
,它是将以该特定字母开头的单词的频率加1。
The output should look like this (using the string I provided below): {'d': 1, 'i': 3, 't': 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))
You never actually use collections.defaultdict
, although you import it. 尽管您导入了它,但您实际上从未真正使用过
collections.defaultdict
。 Initialize d
as defaultdict(int)
, instead of as {}
, and you're good to go. 初始化
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))
Results in: 结果是:
defaultdict(<class 'int'>, {'I': 3, 't': 1, 'd': 1})
You're trying to increase the value of an entry which has yet to be made resulting in the KeyError
. 您正在尝试增加尚未导致
KeyError
的条目的值。 You could use get()
for when there is no entry for a key yet; 当没有键输入时,可以使用
get()
。 a default of 0
will be made ( or any other value you choose ). 默认值为
0
( 或您选择的任何其他值 )。 With this method, you would not need defaultdict
( although very useful in certain cases ). 使用此方法,您将不需要
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))
Sample Output 样本输出
{'I': 3, 'd': 1, 't': 1}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.