[Tutor] how to sort a dictionary by values
kent37 at tds.net
Wed Aug 8 13:09:46 CEST 2007
>> 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 : 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)
In : timeit.Timer('sorted(d.items(), key=operator.itemgetter(1),
reverse=True)', 'from __main__ import d; import operator').timeit(10000)
More information about the Tutor