[Tutor] Having trouble with a dictionary of lists

William Witteman yam at nerd.cx
Fri Sep 4 18:09:19 CEST 2009


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.

#!/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))]
  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)]
  
  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


-- 

yours,

William



More information about the Tutor mailing list