[Tutor] if value in list of dictionaries

Emile van Sebille emile at fenx.com
Tue Sep 28 22:34:59 CEST 2010


On 9/28/2010 11:13 AM Norman Khine said...
> ok, great.
>
> one thing i wanted to ask is how could i extend the class so that i
> can just change the name of the csv file?

Python provides for instance initialization with a class __init__ 
method, so you could modify your class as follows:



def sort_key(option):
     return "other" in option.itervalues(), option["name"]


class BusinessType(Enumerate):
     def __init__(self,cvsfile):
         self.cvsfile = cvsfile
     def get_options(cls):
         context = get_context()
         here = context.resource
         root = here.get_root().handler
         topics = root.get_handler(self.cvsfile)
         options = []
         for index, row in enumerate(topics.get_rows()):
             options.append({'name': row[0], 'value': MSG(row[1])})
         options.sort(key=sort_key)
         return options

Then, instead of invoking:

options = BusinessType().get_options()

You'd write:

options = BusinessType('topics.cvs').get_options()


Emile



More information about the Tutor mailing list