1

I am trying to sort based on frequency and display it in alphabetical order After freq counting , I have a list with (string, count) tuple E.g tmp = [("xyz", 1), ("foo", 2 ) , ("bar", 2)]

I then sort as sorted(tmp, reverse=True) This gives me [("foo", 2 ) , ("bar", 2), ("xyz", 1)]

How can I make them sort alphabetically in lowest order when frequency same, Trying to figure out the comparator function

expected output:[("bar", 2), ("foo", 2 ), ("xyz", 1)]

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Majnu
  • 210
  • 2
  • 10
  • 1
    Hi Dusan, from the link you provided sorted(counter.items(),key = lambda i: i[0]) will just sort based on alphabetic order. I need to freq sort them, then if frequency is same alphabetically. temp = [("xyz", 1), ("foo", 2 ) , ("bar", 2) , ("abc",1)] print sorted(temp,key = lambda i: i[0]) return [('abc', 1), ('bar', 2), ('foo', 2), ('xyz', 1)] – Majnu Dec 02 '20 at 18:05
  • Say hi to your classmate: [Python sort by two fields](https://stackoverflow.com/questions/65095608/python-sort-by-two-fields) – Stef Dec 02 '20 at 18:48

2 Answers2

1

You have to sort by multiple keys.

sorted(tmp, key=lambda x: (-x[1], x[0]))

Source: Sort a list by multiple attributes?.

Dušan Maďar
  • 9,269
  • 5
  • 49
  • 64
0

Use this code:

from operator import itemgetter

tmp = [('xyz',1), ('foo', 2 ) , ('bar', 2)]
print(sorted(tmp, key=itemgetter(0,1)))

This skips the usage of function call.