Home > Software design >  Sorted function in Python dictionary
Sorted function in Python dictionary

Time:08-29

I have a dictionary and I need to print the contents of dictionary first sorted by "value" if there is any value tie then I need to use "key" as a tie breaker so that the keys that have the identical values will be printed in alphabetic order.

final = OrderedDict(sorted(mydict.items(), key=lambda x: (x[1], x[0]), reverse=True))

for key, value in final.items():
    print(f'{key} : {value}')

but when the print command runs, it will display the output like the identical values have not been sorted as expected:

Action : 3
Romance : 2
Horror : 2
History : 2
Comedy : 2
Adventure : 1

The way it's supposed to print must be like:

Action : 3
Comedy : 2
History : 2
Horror : 2
Romance : 2
Adventure : 1

Any thoughts about how can I correct this issue?

CodePudding user response:

{k: v for k, v in sorted(mydict.items(), key=lambda item: (-item[1], item[0]), reverse=False)}

CodePudding user response:

reverse is applied after the sequence has been sorted according to key. You only want the comparison on x[1] to be reversed, not the final ordering. I would use functools.cmp_to_key to convert a comparison function to a key function.

from functools import cmp_to_key

# Redefined from Python 2 since Python 3 dropped it
def cmp(x, y):
    return -1 if x < y else 0 if x == y else 1

def genre_sort(x, y):
    # A bigger count is a smaller genre; otherwise, sort alphabetically
    # by name
    return cmp(y[1], x[1]) or cmp(x[0], y[0])
    
final = OrderedDict(sorted(mydict.items(), key=cmp_to_key(genre_sort)))

CodePudding user response:

You want to reverse the sort for x[1] only so don't pass reverse=True here, instead use negative number trick:

final = OrderedDict(sorted(mydict.items(), key=lambda x: (-x[1], x[0])))
  • Related