I'm trying to figure out why KeyError: 0 pops up when I try to run the program containing the code. -
-
OpenDLG = wx.FileDialog(
-
self.win,
-
message='Please choose the quiz or quizes that you wish to use.',
-
defaultDir=os.getcwd(),
-
defaultFile='',
-
wildcard='*.*',
-
style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR)
-
self.AllWords = {}
-
paths = OpenDLG.GetPaths()
-
wordlistnum = -1
-
if OpenDLG.ShowModal() == wx.ID_OK:
-
for path in paths:
-
textfile = open(path)
-
words = textfile.readlines()
-
french = []
-
english = []
-
Pass = 'no'
-
wordlistnum +=1
-
for word in words:
-
if Pass == 'yes':
-
english.append(word[0:-2])
-
if '#english#' in word:
-
Pass = 'yes'
-
if Pass == 'no':
-
if '#english#' not in word:
-
french.append(word[0:-2])
-
self.AllWords.update(
-
{wordlistnum: {'French': french, 'English': english}})
-
The TXT File that I select contains the fallowing text. -
-
bonjour
-
aurevoir
-
salut
-
#english#
-
hello
-
good bye
-
hey
-
In the hope that someone can help,
Josh
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.
- >>> foo={'a':1,'b':2}
-
>>> foo['c']
-
Traceback (most recent call last):
-
File "<stdin>", line 1, in <module>
-
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 -
>>> value=foo.get('a')
-
>>> print value
-
1
-
>>> value=foo.get('c')
-
>>> print value
-
None
-
>>>
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. -
-
Traceback (most recent call last):
-
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
-
self.GameLoop(evt)
-
File "C:\(path in which I stored the program)\French Quiz_17.pyw.pyw", line 190, in GameLoop
-
self.French = self.AllWords[0]['French']
-
KeyError: 0
-
bvdet 2,851
Recognized Expert Moderator Specialist
Try adding some print statements to determine if your script is doing what you expect.
@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 -
-
OpenDLG = wx.FileDialog(
-
self.win,
-
message='Please choose the quiz or quizes that you wish to use.',
-
defaultDir=os.getcwd(),
-
defaultFile='',
-
wildcard='*.*',
-
style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR)
-
self.AllWords = {}
-
wordlistnum = -1
-
if OpenDLG.ShowModal() == wx.ID_OK:
-
paths = OpenDLG.GetPaths()
-
for path in paths:
-
...
-
That did it!
Funny how things like that matter so much.
I'll have to remember that.
Thanks Josh
Sign in to post your reply or Sign up for a free account.
Similar topics |
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 = {}
|
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'
|
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():
|
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
|
by: Seeker |
last post by:
I essentially copied this program from K&R:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c;
| |
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...
|
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)
|
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);
|
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
|
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...
|
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...
| |
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...
|
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...
|
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...
|
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...
|
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...
|
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...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |