Jorgan Jorgan - 13 days ago 5
Python Question

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. 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. I wrote

d[word[0]] += 1
, which is to add 1 to the frequency of words that start with that particular letter.

The output should look like this (using the string I provided below):
{'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))

Answer

You're trying to increase the value of an entry which has yet to be made resulting in the KeyError. You could use get() for when there is no entry for a key yet; a default of 0 will be made (or any other value you choose). With this method, you would not need defaultdict (although very useful in certain cases).

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

Sample Output

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