468,469 Members | 2,609 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,469 developers. It's quick & easy.

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

1 Bit
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:


Expand|Select|Wrap|Line Numbers
  1. #Created a dictionary
  2. word_dictionary = dict()
  3.  
  4. #opening my filing and setting it in read mode and calling it f
  5. with open('findall.txt', 'r') as f:
  6.   #Getting input from the user
  7.   word = input("Enter the word to search for: ")
  8.   #reading through the file
  9.   content = f.read()
  10.   #counts to see how many words there are
  11.   total = content.count(word)
  12.   #creating a new key value pair for word_dictionary
  13.   word_dictionary['count'] = total
  14.  
  15. #Trying to print the result
  16. print('The word count for ',word, 'is', word_dictionary[word]['count'])
  17.  
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'
6 Days Ago #1
1 1119
Banfa
9,052 Expert Mod 8TB
The problem is in
Expand|Select|Wrap|Line Numbers
  1. 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
Expand|Select|Wrap|Line Numbers
  1. 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.
6 Days Ago #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

reply views Thread by NPC403 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.