The most pythonic way to do it would be to know a little more about the actual data -- specifically, the maximum value you can have -- and then do it like this:
def sortkey((k, v)):
return (maxval - v, k)
items = thedict.items()
items.sort(key=sortkey)
but unless you already know the maximum value, searching for the maximum value means looping through the dict an extra time (with max(thedict.itervalues())
), which may be expensive. Alternatively, a keyfunc version of S.Lott's solution:
def sortkey((k, v)):
return (-v, k)
items = thedict.items()
items.sort(key=sortkey)
An alternative that doesn't care about the types would be a comparison function:
def sortcmp((ak, av), (bk, bv)):
# compare values 'in reverse'
r = cmp(bv, av)
if not r:
# and then keys normally
r = cmp(ak, bk)
return r
items = thedict.items()
items.sort(cmp=sortcmp)
and this solution actually works for any type of key and value that you want to mix ascending and descending sorting with in the same key. If you value brevity you can write sortcmp as:
def sortcmp((ak, av), (bk, bv)):
return cmp((bk, av), (ak, bv))