Home > Enterprise >  How do sort character frequency in descending order
How do sort character frequency in descending order

Time:09-18

import sys
import string
from collections import Counter

input_char = str(sys.argv[1])

c = Counter(input_char.lower())

o = {k: c.get(k) for k in list(sorted(c.keys(),
                                      key=lambda key: (c.get(key)),
                                      reverse=True))[:5]}
print(o)

My input :

python CountPopularChar.py sdsERwweYxcxeewHJesddsdskjjkjrFGe21DS2145o9003gDDS

Current output:

{'s': 7, 'd': 7, 'e': 6, 'j': 4, 'w': 3}

Expected output:

{'d': 7, 's': 7, 'e': 6, 'j': 4, 'w': 3}

So how do I get the output in descending order of character frequency. And if the character have same frequency how do I get it to be printed in ascending ASCII order.

CodePudding user response:

You can sort by a tuple, of the value in the counter and the key itself, but with reverse=True this will give you the same result. So you need to sort only the value in reverse, which you can do by negating it:

o = {k: c.get(k) for k in list(sorted(c.keys(),
                                      key=lambda key: (-c.get(key), key),
                                      ))[:5]}

Output:

{'d': 7, 's': 7, 'e': 6, 'j': 4, 'w': 3}

You can also use most_common to avoid the slicing:

o = {t[0] : t[1] for t in sorted(c.most_common(5),
                                 key=lambda t:(-t[1], t[0])
                                 )}

The output is the same.

CodePudding user response:

You can use most_common for this:

string = "sdsERwweYxcxeewHJesddsdskjjkjrFGe21DS2145o9003gDDS"
c = Counter(string.lower())
dict(sorted(c.most_common(5), key=lambda x: (x[1], x[0]),reverse=True))
{'s': 7, 'd': 7, 'e': 6, 'j': 4, 'w': 3}
  • Related