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:
Python
# 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' ])
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'

What I have tried:
I tried searching google for the key error that I'm getting but I wasn't able to find any results online. I'd suggest to start here: 5. Data Structures — Python 3.9.5 documentation [ ^ ].
Take a look at this small piece of code:
Python
>>> tel = { ' jack' : 4098 , ' sape' : 4139 } >>> tel[ ' guido' ] = 4127 { ' jack' : 4098 , ' sape' : 4139 , ' guido' : 4127 } >>> tel[ ' jack' ] >>> del tel[ ' sape' ] >>> tel[ ' irv' ] = 4127
So, to add key-value-pair to your dictionaty, you should use:
Python
word_dictionary[ ' your_word_here' ] = count_of_word word_dictionary[ ' count' ] = total You are using the key 'count' instead of the word chosen by the user. It should be:
Python
word_dictionary[word] = total
  • Read the question carefully.
  • Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  • If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  • Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question. Let's work to help developers, not make them feel stupid.
  •