Thanks Daniel Yes, it was multiple keys not just 'department'. Will have a go and do some more reading on lambda.
cheers -sam On Thu, Dec 17, 2009 at 8:38 PM, Daniel Roseman <dan...@roseman.org.uk> wrote: > On Dec 17, 6:23 am, Sam Walters <mr.sam...@gmail.com> wrote: >> Hi I have been reading stuff like: >> >> http://wiki.python.org/moin/SortingListsOfDictionaries >> >> I want to sort a list of dictionaries (alphanumeric values) by >> multiple keys (achieved with code below). However I would like to >> customise the comparator to put empty objects last. >> >> eg: >> >> def orderBasedOnDepartment(items): >> return sorted(items, key=lambda >> items:(items['department'],items['suburb'],items['state'],items['distanceNm >> '])) >> >> for instance if the dictionary containing key: department = None >> then I would like it placed after everything else instead of before. >> >> Changed from: >> >> None >> A >> Aa >> Ab >> C >> D >> >> To: >> >> A >> Aa >> Ab >> C >> D >> None >> >> Any help would be appreciated so I can have a day off for christmas. >> >> -sam > > Not entirely clear what you're doing - is it just department=None you > want last, or should None go last whatever key it is associated with? > > Anyway, the trick here is to remember that there's nothing special > about a lambda, you can use a normal function as a key just as well. > So: > > def sort_none_last(item): > key = [] > nones = [] > for k in ('department', 'suburb', 'state', 'distanceNm'): > if item[k] is None: > none.append(None) > else: > key.append(item[k]) > key.extend(nones) > return tuple(key) > > sorted(items, key=sort_none_last) > > -- > > You received this message because you are subscribed to the Google Groups > "Django users" group. > To post to this group, send email to django-us...@googlegroups.com. > To unsubscribe from this group, send email to > django-users+unsubscr...@googlegroups.com. > For more options, visit this group at > http://groups.google.com/group/django-users?hl=en. > > > -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.