Pythonic way with more than one max possible

woooee woooee at gmail.com
Wed Jul 20 01:37:37 EDT 2011


> 1. In this dict, if there is a UNIQUE max value, then its *key* is the
> winner.
> 2. If there are any TIES for max value, then the *key* 'b' is the
> winner by default.

This will store the max value(s) in a list.  In case of a tie, you can
take the first value in the list, but it may be different than 'b'
since dictionary keys are in hash order, not in the order they were
entered.  You can decide if you want the smallest key, or whatever
criterion is best.

the_dict = {'a':1, 'b':2, 'c':0, 'd':1, 'a0':2}
winners = [['*', -999]]
for key in the_dict:
    max_value = winners[0][1]  ## only lookup once
    dict_value = the_dict[key] ##  "     "     "
    if dict_value > max_value:
        winners = [[key, dict_value]]
    elif dict_value == max_value:
        winners.append([key, dict_value])

print winners



More information about the Python-list mailing list