sorting a dictionary

Alex Martelli aleax at aleax.it
Wed Feb 5 10:09:14 EST 2003


Terry Reedy wrote:
   ...
>> def key_of_highest(d):
>>     mv = max(d.values())
>>     for k in d:
>>         if d[k] == mv:
>>             break
>>     return k
>>
>> Well, it may not be O(N), but it avoids spurious assignments. :^)
> 
> It is O(n) (assuming that d.values() is); there is only the matter of
> the constant, and the space for d.values() (versus the iterator
> version).

max(d.itervalues()) should solve the space problem.  If you want
to determine the times, of course, you need to run the various
possible solutions *on dictionaries that are representative of
problems your application will really solve* -- running on other
dictionaries whose contents are not representative of your
problems will give you little practical help.


Alex





More information about the Python-list mailing list