[Tutor] Having trouble with a dictionary of lists
William Witteman
yam at nerd.cx
Thu Sep 3 20:01:11 CEST 2009
I am trying to create a CSV file of sorted similar lists, arranged so
that differences are easily compared in a spreadsheet. I am
encountering the following error, however:
IndexError: list assignment index out of range
On the indicated line below. I understand the error, but I don't
understand why I am getting it. Can anyone shed some light on this?
Thanks.
#!/usr/bin/python
"""
Take a collection of lists, combine them into one list, deleting duplicates.
Sort the list and use it as the leftmost column of a table. Then put each
lists contents into the table, one per column, with the elements aligned
with the leftmost (index) column.
"""
import os, sys, csv
def cmpss(filename,*sslists):
"""Write a CSV file from the collection of lists."""
if os.path.exists(filename):
print("%s exists: please choose another filename." % filename)
sys.exit(1)
else:
try:
fn = csv.writer(open(filename, "w"))
except IOError:
print("There is a problem opening the requested file. Sorry.")
sys.exit(1)
termdict = {}
for sslist in sslists:
for term in sslist:
termdict[term] = ""
termlist = termdict.keys()
termlist.sort()
sortedtermdict = {}
number_of_commas = 1 - len(sslists)
for term in termlist:
sortedtermdict[term] = ["" for x in range(number_of_commas)]
for sslist in sslists:
counter = 0
for term in sslist:
# The line below is where my program barfs.
sortedtermdict[term][counter] = term
counter = counter + 1
for row in sortedtermdict:
fn.writerow(row)
--
yours,
William
More information about the Tutor
mailing list