[Tutor] how to sort a dictionary by values

shawn bright 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
shawn

On 8/8/07, Kent Johnson <kent37 at tds.net> wrote:
>
> Tiger12506 wrote:
> >> Just curious: Is there a reason to use __getitem__() over itemgetter
> (used
> >> in the example in my reply)?
> >
> > __getitem__ is a method builtin to a dict object. itemgetter 1) has to
> be
> > 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 [27]: import random
> In [28]: d = dict( (i, random.random()) for i in range(1000) )
> In [29]: import timeit
> In [34]: timeit.Timer('sorted(d.keys(), key=d.__getitem__,
> reverse=True)', 'from __main__ import d').timeit(10000)
> Out[34]: 7.3717570304870605
> In [38]: timeit.Timer('sorted(d.items(), key=operator.itemgetter(1),
> reverse=True)', 'from __main__ import d; import operator').timeit(10000)
> Out[38]: 8.2723259925842285
>
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070808/5f0ea49c/attachment.html 


More information about the Tutor mailing list