Thursday, September 18, 2008

Python Code:: Sort by Key and Subkey in a List of Dictionaries

Here is a semi clear way to perform this function. There is probably a more elegant way to do this or even some snazzy library method, but this shows some of the guts of how this might be done. I am confident this can be rewritten to perform this is linear time or better. Again this is quick and dirty, like "Ah crap, I need this now and I can optimize later" type of thing:

def sortResults(self, unsort_rs, orderby, desc, subsortkey=None):
   list_rs = list(unsort_rs)
   result_rs = sorted(list_rs, key=itemgetter(orderby))
   if subsortkey:
     sub_list, complete_list = [], []
     for i in xrange(len(result_rs)):
       sub_list.append(result_rs[i])
       try:
          if result_rs[i+1][orderby] != result_rs[i][orderby]:
            complete_list += sorted(sub_list, key=itemgetter(subsortkey))
            sub_list = []
        except IndexError:
            complete_list += sorted(sub_list, key=itemgetter(subsortkey))
     result_rs = complete_list
   if desc == 1:
     result_rs.reverse()
   sorted_rs = tuple(result_rs)
   return sorted_rs