[Tutor] how to sort a dictionary by values

Kent Johnson kent37 at tds.net
Wed Aug 8 13:09:46 CEST 2007

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


More information about the Tutor mailing list