473,385 Members | 2,015 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

How to fix "list index out of range" error?

This is my first program of any sort I am getting this error

File "karenrosen5.py", line 162, in <module>
record.append(triad("NoReleve",line))
File "karenrosen5.py", line 115, in triad
item = data[fields2[key]]
IndexError: list index out of range

The code in question is
Expand|Select|Wrap|Line Numbers
  1.  
  2. def triad(key,data):
  3.     try:
  4.         assert key in fields
  5.     except:
  6.         print "key %s not found" %key
  7.         raise ValueError,key
  8.     item = data[fields2[key]]
  9.     if key in noblanks:
  10.         item = item.replace(" ","")
  11.     if key.startswith("_"):
  12.         key = key.replace("_","")    # hack for double column names
  13.     if isblank(item):
  14.         if defaults:
  15.             if key in defaults.keys():
  16.                 return  "<%s>"%key+defaults[key]+"</%s>"%key
  17.             else:
  18.                 return  "<%s>"%key+"(inconnu)</%s>"%key
  19.         else:
  20.             print line
  21.             raise BadLine
  22.     return "<%s>"%key+item+"</%s>"%key
  23.  
  24. defaults = {"NAS":"000000000","A_DateNaissance":"1/1/20","B1_NbJoursGarde":"0"}
  25. noblanks = ["NAS","CodePostal"]
  26.  
  27.  
  28. filename = "KR.tsv"
  29. outname = "KR5.xml"
  30.  
  31. outfile = file(outname,"w")
  32.  
  33. data = [item.strip().split("\t") for item in file(filename).readlines()]
  34. fields = data[0]
  35. fields2 = dict([(item[1],item[0]) for item in enumerate(fields)])
  36.  
  37. # hack for double column names
  38. fields2["_Prenom"]=4
  39. fields2["_NomFamille"]=3
  40.  
  41. fields += "_Prenom _NomFamille".split()
  42. # end hack for double column names
  43.  
  44. print fields2
  45.  
  46. outfile.write(prefix)
  47.  
  48. for line in data[1:]:
  49.     if not [item for item in line if (not isblank(item))]:
  50.         break     # TSV file ends with many blank lines; exit and clean up on first one
  51.     try:
  52.         record = ["\n\n<R>"]
  53.  
  54.         record.append(triad("Annee",line))
  55.         record.append(triad("NoReleve",line))
  56.  
  57.         record.append("<Payeur>")
  58.  
  59.         record.append(triad("NAS",line))
  60.         record.append(triad("_NomFamille",line))
  61.         record.append(triad("_Prenom",line))
  62.  
  63.         record.append("<Adresse>")
  64.         record.append(triad("Ligne1",line))
  65.         record.append(triad("Ville",line))
  66.         record.append(triad("Province",line))        
  67.         record.append(triad("CodePostal",line))
  68.         record.append("</Adresse>")
  69.  
  70.         record.append("</Payeur>")
  71.  
  72.         record.append("<Enfant>")
  73.  
  74.         record.append(triad("NomFamille",line))
  75.         record.append(triad("Prenom",line))
  76.         record.append(triad("A_DateNaissance",line))
  77.  
  78.         record.append("<CaseB>")
  79.         record.append(triad("B1_NbJoursGarde",line))
  80.         record.append("</CaseB>")
  81.  
  82.         record.append("<Montants>")
  83.         record.append(triad("C_FraisPayes",line))
  84.         record.append("</Montants>")
  85.  
  86.         record.append("</Enfant>")
  87.  
  88.         record.append("</R>") 
  89.         record = "\n".join(record)
  90.         outfile.write(record)
  91.     except BadLine:
  92.         pass
  93.  
  94.  
Feb 2 '11 #1
1 7999
bvdet
2,851 Expert Mod 2GB
To debug this, make a series of print statements prior to the line with the error.
Expand|Select|Wrap|Line Numbers
  1. print data
  2. print fields2
  3. print key
The error message is telling you that the list index is not valid for the list. Example:
Expand|Select|Wrap|Line Numbers
  1. >>> s = [0,1,2,3,4,5]
  2. >>> s[6]
  3. Traceback (most recent call last):
  4.   File "<interactive input>", line 1, in ?
  5. IndexError: list index out of range
  6. >>> 
Feb 2 '11 #2

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

Similar topics

10
by: Andrew Dalke | last post by:
Is there an author index for the new version of the Python cookbook? As a contributor I got my comp version delivered today and my ego wanted some gratification. I couldn't find my entries. ...
9
by: Robert Brown | last post by:
If I use _reverse_ wildcard search will it always result in a table scan? Is it possible to get the DB (Oracle or SQL server) to use indexes when doing reverse wildcard match? let's say I have:...
16
by: ES Kim | last post by:
"A Book on C" explains a technique to use an arbitrary array index range. int* p = malloc(sizeof(int) * 10) - 1; This way, the allocated array can be accessed with index range 1 ~ 10, not 0 ~...
8
by: sam | last post by:
hey everybody, this is my first time posting here. i'm pretty new to python and programming in general (as you'll soon work out for yourselves...) i'm trying to code a version of a selection...
85
by: Russ | last post by:
Every Python programmer gets this message occasionally: IndexError: list index out of range The message tells you where the error occurred, but it doesn't tell you what the range and the...
0
by: muzu1232004 | last post by:
If I have a table t1 with a column a as follows A 1 1 1 1 1 1 1
0
by: ferlarroca | last post by:
Hi, I am trying to copy a range below another one...... I have defined two ranges as follow: Dim r1 As Range Dim r2 As Range Set r1 = Sheets("Old Index").Range("A9:A200, H9:H200, K9:K200")...
1
by: Steffen Stellwag | last post by:
Truely is often better to scan a table in full passing by an index , but if you can force the optimizer to use an index via a hint for testing and comparing the results. But the index in the...
21
by: Bill Cunningham | last post by:
I have create these 2 files. Called main.c and atr.c. They seem to work pretty well. I just wanted to submit them to see what if any errors others that know more might find. Thanks. atr.c ...
1
by: evilbungle | last post by:
Hi, I know this is for Access but I was hoping someone may know about Excel and can help me. I have created a Function in VBA for looking up a value in a grid it works fine but only if I place...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.