[Tutor] Having trouble with a dictionary of lists
Emile van Sebille
emile at fenx.com
Fri Sep 4 18:54:20 CEST 2009
On 9/4/2009 9:09 AM William Witteman said...
> On Thu, Sep 03, 2009 at 11:26:35AM -0700, Emile van Sebille wrote:
>
> Thanks to Emile for pointing out the error. There were several other
> errors - initiating the counter in the loop (d'oh!), premature sorting
> of the dictionary by keys, not providing an index row for the output
> file, not returning anything from my function, and probably others.
>
> Here is how it looks now - any pointers, stylistic or otherwise, are
> welcome. It does, however, work.
That's normally when I stop looking at it. If I'm lucky, I'll never
need to work on it again. If and when I do, that's when I clean it up
in the area that needs attention. It's way to easy IMHO to turn one-off
projects into time-sinks.
Anyway, some notes interspersed below...
Emile
>
> #!/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)
> toprow = [x for x in range(len(sslists))]
This looks like toprow is simply range(len(sslists))...
> toprow.insert(0, "index")
> fn.writerow(toprow)
>
> termdict = {}
> number_of_columns = len(sslists)
>
> for sslist in sslists:
> for term in sslist:
> termdict[term] = ["" for x in range(number_of_columns)]
this might also be said [""]*number_of_columns
>
> sortedtermlist = termdict.keys()
> sortedtermlist.sort()
>
> counter = 0
>
> for sslist in sslists:
> for term in sslist:
> #debug print(counter)
> #debug print(term)
> termdict[term][counter] = term
> counter = counter + 1
>
> for term in sortedtermlist:
> row = [term]
> row.extend(termdict[term])
> fn.writerow(row)
>
> return termdict
>
>
More information about the Tutor
mailing list