[Tutor] how to sort a dictionary by values
nephish at gmail.com
Wed Aug 8 14:02:33 CEST 2007
sorry all, i did mean greatest to least, thanks for all the help here
On 8/8/07, Kent Johnson <kent37 at tds.net> wrote:
> Tiger12506 wrote:
> >> Just curious: Is there a reason to use __getitem__() over itemgetter
> >> in the example in my reply)?
> > __getitem__ is a method builtin to a dict object. itemgetter 1) has to
> > imported 2) is more generically used, therefore probably using a more
> > generic/slower algorithm
> itemgetter() written in C and should be pretty fast. The actual sort
> algorithm is the same in either case, in fact the list of keys to be
> sorted is the same in either case.
> On my computer my version seems to be a little faster on random data but
> as I noted in a separate email, the results are different so the
> algorithm should be chosen based on the desired results.
> In : import random
> In : d = dict( (i, random.random()) for i in range(1000) )
> In : import timeit
> In : timeit.Timer('sorted(d.keys(), key=d.__getitem__,
> reverse=True)', 'from __main__ import d').timeit(10000)
> Out: 7.3717570304870605
> In : timeit.Timer('sorted(d.items(), key=operator.itemgetter(1),
> reverse=True)', 'from __main__ import d; import operator').timeit(10000)
> Out: 8.2723259925842285
> Tutor maillist - Tutor at python.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor