473,569 Members | 2,634 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why does this cause KeyError: 0?

19 New Member
I'm trying to figure out why KeyError: 0 pops up when I try to run the program containing the code.



Expand|Select|Wrap|Line Numbers
  1.  
  2. OpenDLG = wx.FileDialog(
  3.             self.win,
  4.             message='Please choose the quiz or quizes that you wish to use.',
  5.             defaultDir=os.getcwd(),
  6.             defaultFile='',
  7.             wildcard='*.*',
  8.             style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR)
  9.         self.AllWords = {}
  10.         paths = OpenDLG.GetPaths()
  11.         wordlistnum = -1
  12.         if OpenDLG.ShowModal() == wx.ID_OK:
  13.             for path in paths:
  14.                 textfile = open(path)
  15.                 words = textfile.readlines()
  16.                 french = []
  17.                 english = []
  18.                 Pass = 'no'
  19.                 wordlistnum +=1
  20.                 for word in words:
  21.                     if Pass == 'yes':
  22.                         english.append(word[0:-2])
  23.                     if '#english#' in word:
  24.                         Pass = 'yes'
  25.                     if Pass == 'no':
  26.                         if '#english#' not in word:
  27.                             french.append(word[0:-2])
  28.                 self.AllWords.update(
  29.                     {wordlistnum: {'French': french, 'English': english}})
  30.  


The TXT File that I select contains the fallowing text.



Expand|Select|Wrap|Line Numbers
  1.  
  2. bonjour
  3. aurevoir
  4. salut
  5. #english#
  6. hello
  7. good bye
  8. hey
  9.  
In the hope that someone can help,
Josh
Jan 23 '09 #1
6 55543
bvdet
2,851 Recognized Expert Moderator Specialist
Josh,

Can you post the full error message, including tracebacks? KeyError implies a problem with a dictionary key.
Jan 23 '09 #2
kaarthikeyapreyan
107 New Member
Expand|Select|Wrap|Line Numbers
  1. >>> foo={'a':1,'b':2}
  2. >>> foo['c']
  3. Traceback (most recent call last):
  4.   File "<stdin>", line 1, in <module>
  5. KeyError: 'c'
Key error is raised when a mapping (dictionary) key is not found in the set of existing keys. I think you are trying to access a non-existing dictionary key; post your complete code and error in case u don find the solution ;)
just in case you don prefer to get the key error use the get() method associated with the dictionary.get( ) returns a none value in case the key is not found
Expand|Select|Wrap|Line Numbers
  1. >>> value=foo.get('a')
  2. >>> print value
  3. 1
  4. >>> value=foo.get('c')
  5. >>> print value
  6. None
  7. >>> 
Jan 23 '09 #3
josh001
19 New Member
But why is self.AllWords empty?
Is it something to do with the way I accessed the text file?

Here is the full Error code.
Expand|Select|Wrap|Line Numbers
  1.  
  2. Traceback (most recent call last):
  3.   File "C:\Documents and Settings\Joshua Leihe\My Documents\My Projects\NewProjects\Joshua\Python projects\French quiz\French Quiz_17.pyw.pyw", line 261, in French
  4.     self.GameLoop(evt)
  5.   File "C:\(path in which I stored the program)\French Quiz_17.pyw.pyw", line 190, in GameLoop
  6.     self.French = self.AllWords[0]['French']
  7. KeyError: 0
  8.  
Jan 23 '09 #4
bvdet
2,851 Recognized Expert Moderator Specialist
Try adding some print statements to determine if your script is doing what you expect.
Jan 23 '09 #5
kaarthikeyapreyan
107 New Member
@josh001
Get the paths only after the event in the dialog completes. There were no files that were returned from the file dialog in its initial state, and hence self.AllWords was empty when u accessed it which caused the KeyError. try doing it this way

Expand|Select|Wrap|Line Numbers
  1.  
  2. OpenDLG = wx.FileDialog(
  3.             self.win,
  4.             message='Please choose the quiz or quizes that you wish to use.',
  5.             defaultDir=os.getcwd(),
  6.             defaultFile='',
  7.             wildcard='*.*',
  8.             style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR)
  9.         self.AllWords = {}
  10.         wordlistnum = -1
  11.         if OpenDLG.ShowModal() == wx.ID_OK:
  12.             paths = OpenDLG.GetPaths()
  13.             for path in paths:
  14.                 ...
  15.  
Jan 28 '09 #6
josh001
19 New Member
That did it!
Funny how things like that matter so much.
I'll have to remember that.

Thanks Josh
Jan 28 '09 #7

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

Similar topics

0
1613
by: Norman Shelley | last post by:
Is there a way to get at the object one is trying to access with a key to list out all the possible keys? See the except clause below. #!/usr/bin/env python2.2 from inspect import * import sys program = """ abc = {}
1
5305
by: | last post by:
Hello. Maybe someone will help me with this KeyError: ............................. Traceback (most recent call last): File "C:\Python\tabla.py", line 929, in -toplevel- tablesDirectory = tablesDirectoryPrefix + os.environ File "C:\Python23\lib\os.py", line 417, in __getitem__ return self.data KeyError: 'REMOTE_ADDR'
3
5093
by: Rune Strand | last post by:
I'm experiencing strange errors both with pickle and cPickle in the below code: import cPickle as pickle #import pickle from string import ascii_uppercase from string import ascii_lowercase def createData():
4
8034
by: homepricemaps | last post by:
i have an href which looks like this: <td class="all"> <a class="btn" name="D1" href="http://www.cnn.com"> </a> here is my code
18
2256
by: Seeker | last post by:
I essentially copied this program from K&R: #include <stdio.h> #include <stdlib.h> int main() { int c;
10
2465
by: Mythmon | last post by:
I am trying to make a program that will basically simulate a chess clock in python. To do this I have two threads running, one that updates the currently running clock, and one that watches for a keypress. I am using the effbot Console module, and that is where I get the events for the keypresses. But when I press space it crashes shortly...
3
3964
by: nyenyec | last post by:
urllib.quote chokes on unicode in 2.4.4. 2.4.4 (#1, Oct 18 2006, 10:34:39) Traceback (most recent call last): File "<stdin>", line 1, in ? File "/Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/urllib.py", line 1117, in quote res = map(safe_map.__getitem__, s)
92
6138
by: Heinrich Pumpernickel | last post by:
what does this warning mean ? #include <stdio.h> int main() { long l = 100; printf("l is %li\n", l * 10L);
2
7833
by: christof | last post by:
Hi, I am using pickle/unpickle to let my program save its documents to disk. While this it worked stable for a long time, one of my users now complained, that he had a file which can't be loaded. The traceback is: File "pickle.pyo", line 1374, in loads File "pickle.pyo", line 858, in load
0
7701
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7615
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7677
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...
0
7979
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...
0
6284
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...
1
5514
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...
0
5219
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...
0
3653
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...
0
3643
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.