473,661 Members | 2,501 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

1 New Member
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'
Jun 8 '21 #1
1 2708
Banfa
9,065 Recognized Expert Moderator Expert
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.
Jun 8 '21 #2

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

Similar topics

0
1738
by: Imran | last post by:
I m getting this error when i open asp.net Form Design View. "The file failed to load in the Web Form Designer. PLease Correct the following error, then load it again. The designer could not be shown for this file because none of the classes within it can be designed. The designer inspected the following classes in the file: form1.aspx -- the designer for the base class ' System.Web.UI.Page' is not installed."
1
2413
by: dipesh | last post by:
I am getting error when trying to Add Web Reference in Visual Studio 2005. "Some of the files required for web references are not installed"
1
1927
by: siddu | last post by:
Hi All, I have to do one task. First i need to copy files from vss and run bat files.i have a document with all steps. step 1: we have to take files from vss by using getlatestversion option and copy it to some where in local. step2: In Dos command prompt i have to run 2 .bat files
1
1233
by: PulkitZery | last post by:
Hi, I am getting the following error when calling a method which i defined in web service. Any Idea? ---------------------------------------------------------------------------------------------------------------- System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: http://tempuri.org/MinuteTraqService/Data_1_0/MailMsg. at...
2
1524
by: mak1084 | last post by:
i friends i'm getting this error when i execute the insert query.... what is the problem and how i can execute the my query? :?
1
2503
by: jonny | last post by:
Went from using Visual Web Develop express to Visual Studio 2005 and getting error when trying to open project. Error message: "One or more projects in the solution could not be loaded for the following reason(s): The project file or web has been moved, renamed or is not on your computer.
0
621
by: =?Utf-8?B?UmF2aQ==?= | last post by:
Hi, I have WCF service and integrated with STS (WS-Federation). The Service exposes 5 endpoints Win, UNT and Federated Windows, Federated UNT and Mex endpoint. My STS Service exposes 3 endpoints WIN, UNT and Mex. I am getting error when I sent a request from a client to WCF Service Fed-Win/ Fed-Unt endpoints. But it is passing for the regular Win and Unt endpoints.
4
4015
by: sumit kale | last post by:
Hi, Can somebody help me resolve my problem ? I am getting error when calculating total using unbound textfiled in subform. I have a main form called purchase_register_master and a subform called purchase_register_details, In sub form i have a unbound textfield called txt_Total_Amount where in i am calculating total amount for different items purchased by giving following code in control source. ContolSource: =Sum() In my main form i...
1
1545
by: NareshN | last post by:
Hi, I am getting error in following stored procedure in where condition Must declare the scalar variable "@CampaignId".I already declared CampaignId but still getting error.Please see where condition which is in bold letters. If i give value its working like where CampaignID=1 alter PROCEDURE SAR_Sp_GetForecastedHC(@date1 DATETIME, @date2 DATETIME, @date3 DATETIME, @date4 DATETIME,@CampaignId int) AS DECLARE @query VARCHAR(MAX)
1
1572
by: pallabtrue | last post by:
hello bytes friends, I am trying to run simple perl script with linux command where I am using 'awk' command and my perl script is ------------------------------------------------ #!/usr/bin/perl -w use strict; while (my $line =<>) { chomp $line;
1
8545
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8633
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7364
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6185
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5653
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4179
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2762
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1986
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1743
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.