Trouble sorting a list of objects by attributes

Robocop bthayre at physics.ucsd.edu
Fri Feb 6 19:43:48 EST 2009


On Feb 6, 2:41 pm, Stephen Hansen <apt.shan... at gmail.com> wrote:
> > I think there may have been a misunderstanding.  I was already using
> > attrgetter, my problem is that it doesn't appear to be sorting by the
> > argument i give it.  How does sort work with strings?  How about with
> > datetime.time or datetime.date?
>
> You were using the attrgetter, but it looks like you weren't doing it correctly:
>
>     timesheets.sort(key=operator.attrgetter('string'))
>
> You don't specify a type, be it string or date or anything: you
> specify the /name/ of the attribute to get. It'll handle sorting by
> any data type that has an order to it without you having to worry
> about it at all. Strings, ints, dates, times.
>
> It should be:
>
>    timesheets.sort(key=operator.attrgetter("department"))
>
> If you want to sort by the value of the "department" attribute, which
> happens to be a string.
> If you want to sort by the "date" attribute, which happens to be a
> datetime.date, you do:
>    timesheets.sort(key=operator.attrgetter("date"))
>
> Where date is not a datatype a la datetime.date, but the name of an
> attribute on your TimeSheet instances.
>
> --S

Yeah this i totally understand.  In my code i was using attrgetter
correctly, in the above answer i used string to represent the datatype
of the attribute, not what i actually put in there.  More my laziness
than anything else.  The problem boiled down attrgetter taking
multiple arguments in 2.5, but only one in 2.4.  Thanks for the input
though.



More information about the Python-list mailing list