Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
Python, Lua and Tcl - public course schedule [here]
Private courses on your site - see [here]
Please ask about maintenance training for Perl, PHP, Java, C, C++, Ruby, MySQL and Linux / Tomcat systems
Python key error

Posted by PaulStat (PaulStat), 6 October 2010
Ok so I have the following code, ReadMyData passes a tuple of dictionaries to InsertChannelPrograms, which then builds a values tuple and appends it to a list depending on how big the input tuple (listDict) was.

def ReadMyData(self,datFile):
  channelID = datFile[:-4]
  fields = ["PROGTITLE", "SUBTITLE",
             "EPISODE", "YEAR", "DIRECTOR",
             "PERFORMERS","PREMIERE", "FILM",
             "NEWSERIES","DEAFSIGNED", "BNW",
             "DESCRIPTION","CHOICE", "DATE",
             "STARTTIME", "ENDTIME", "DURATION"]
  delim    = '~'
  lineReader   = csv.DictReader(open("./input/" + datFile,'rb'),
  # Read the header lines
  channelPrograms = []
  for row in lineReader:
  for i in range(len(channelPrograms)):
     if (i+3) < len(channelPrograms):
     elif (i+2) < len(channelPrograms):
     elif (i+1) < len(channelPrograms):

def InsertChannelProgrammes(self,channelID,listDict):
  columns = []
  for i in range(len(listDict)):
     tempDict = listDict[i]
     valuesTuple = (channelID,self.FormatDate(tempDict["DATE"]),tempDict["STARTTIME"])
  if len(columns) > 0:

This code gives me the error

Traceback (most recent call last):
 File "", line 82, in <module>
 File "", line 52, in ReadMyData
 File "", line 58, in InsertChannelProgrammes
   tempDict = listDict[i]
KeyError: 0

I simplified the concept to see if it would work and it does, see below:

>>> dateList = []
>>> dateDict1 = {'DATE': '2010-06-20'}
>>> dateDict2 = {'DATE': '2010-06-28'}
>>> dateList.append(dateDict1)
>>> dateList.append(dateDict2)
>>> def PassList():
...    TakeList((dateList[0],dateList[1]))
>>> def TakeList(listDict):
...    for i in range(len(listDict)):
...       tempDict = listDict[i]
...       print tempDict["DATE"]
>>> PassList()

So any ideas why I'm getting this?

Posted by dcorking (David Corking), 25 February 2011
Paul, You should be able to get more detail with the debugger.

Meanwhile, my guess is that the KeyError happens because (at the time of the traceback) listDict is not a list of dictionaries but a dictionary.

Take a look at this line

I made a quick demo program to illustrate my idea

myDictCoats = { "tree" : "bark" , "dog" : "fur" }
myDictFrench = { "boy": "garcon", "fish": "poisson"}

myTupleOfDicts = (myDictCoats, myDictFrench)


print "This is when your program seems to work: two appended dictionaries"
# compare the next line to self.InsertChannelProgrammes(channelID,(channelPrograms[i], channelPrograms[i+1]))
good = (myTupleOfDicts [i], myTupleOfDicts [i+1])
print good
print ("This object has"), type(good), (" and length"), len(good)
print "Zeroth element is", good [i]

print "I suggest that this is the failure point: one dictionary"
# compare the next line to self.InsertChannelProgrammes(channelID,(channelPrograms[i]))
broken = (myTupleOfDicts [i])
print broken
print "This object has", type(broken), (" and length"), len(broken), "\n"
# As this is of type 'dictionary', not a tuple, print broken [i] will give KeyError: i

# A quick fix might be easy: add a comma
print "I added a comma to the assignment statement"
fixed = (myTupleOfDicts [i],)
print fixed
print ("This object has"), type(fixed), (" and length"), len(fixed)
print "Zeroth element is", fixed [i]

Sorry about all the repetition.
Run my demo with the debugger or the interpreter to play with it.

My output is Quote:
This is when your program seems to work: two appended dictionaries
({'tree': 'bark', 'dog': 'fur'}, {'boy': 'garcon', 'fish': 'poisson'})
This object has <type 'tuple'>  and length 2
Zeroth element is {'tree': 'bark', 'dog': 'fur'}

I suggest that this is the failure point: one dictionary
{'tree': 'bark', 'dog': 'fur'}
This object has <type 'dict'>  and length 2

I added a comma to the assignment statement
({'tree': 'bark', 'dog': 'fur'},)
This object has <type 'tuple'>  and length 1
Zeroth element is {'tree': 'bark', 'dog': 'fur'}

I think you might be able to fix your code if you add a comma near the end of line 52

If that doesn't help, you could try Graham's new forum,

This page is a thread posted to the opentalk forum at and archived here for reference. To jump to the archive index please follow this link.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2018: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01225 708225 • FAX: 01225 793803 • EMAIL: • WEB: • SKYPE: wellho