I'm able to count all of the words in my .txt file but I'm having a hard time putting that result inside of my dictionary. I tried adding a new key value pair to my dictionary, I don't know if I did it right. I called the key "count" and I am calling the value "total". I'm trying to grab the variable "total" and make it the value of my dictionary. I don't if you are allowed do that or not but I could use some help. I don't if it has anything to do with the error that I'm getting but the error message is right below my code. Here's my code:
I get an error when I run the program this is what it says:
Quote:
Enter the word to search for: life
Traceback (most recent call last):
File "main.py", line 13, in <module>
print('The word count for ',word, 'is', word_dictionary[word]['count'])
KeyError: 'life'
Code:
#Created a dictionary
word_dictionary = dict()
#opening my filing and setting it in read mode and calling it f
with open('findall.txt', 'r') as f:
#Getting input from the user
word = input("Enter the word to search for: ")
#reading through the file
content = f.read()
#counts to see how many words there are
total = content.count(word)
#creating a new key value pair for word_dictionary
word_dictionary['count'] = total
#Trying to print the result
print('The word count for ',word, 'is', word_dictionary[word]['count'])
Quote:
Enter the word to search for: life
Traceback (most recent call last):
File "main.py", line 13, in <module>
print('The word count for ',word, 'is', word_dictionary[word]['count'])
KeyError: 'life'
Comment