Why am I getting a key error when I print my dictionary?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • adamb123
    New Member
    • Jun 2021
    • 1

    Why am I getting a key error when I print my dictionary?

    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:


    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'])
    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'
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    The problem is in
    Code:
    word_dictionary[word]['count']
    The variable word contains the value 'life' but you have never created a key 'life' you only created a key 'count'. Additionally you are using double [] on a type that only really uses single [] for data access.

    Did you mean to write
    Code:
    word_dictionary['count']
    ?

    However I also note that the use of a dictionary in this code is unnecessary, you could equally well just use the variable total at line 16. Unless you are planning to alter the code to count the occurrence of multiple or all words. However in that case you would be better off using the word you are counting as the key not 'count' so that your dictionary can store multiple values.

    Comment

    Working...