Home > Software engineering >  How to sort the frequency of each letter in a descending order Python?
How to sort the frequency of each letter in a descending order Python?

Time:03-02

import collections

MY_FUN_STR = filter(str.isalpha, (str.lower("ThE_SLATe-Maker")))

frequencies = collections.Counter(MY_FUN_STR)

a = sorted(frequencies, reverse=True)

for letter in frequencies:
    print ('{} appears {}'.format(letter, frequencies[letter])   " times")

The output now is:

t appears 2 times
h appears 1 times
e appears 3 times
s appears 1 times
l appears 1 times
a appears 2 times
m appears 1 times
k appears 1 times
r appears 1 times

CodePudding user response:

There are two issues with your code:

  1. You're sorting the output from the counter, but never actually using it inside the subsequent for loop.
  2. Your sorting is based on lexicographical ordering, not the frequency of the actual keys. You need to pass in an explicit key parameter to sorted(), so that the function knows to sort based on frequency.

Here is a code snippet that resolves both of these issues:

import collections

MY_FUN_STR = filter(str.isalpha, (str.lower("ThE_SLATe-Maker")))

frequencies = collections.Counter(MY_FUN_STR)

a = sorted(frequencies, key=lambda x: frequencies[x], reverse=True)

for letter in a:
    print ('{} appears {}'.format(letter, frequencies[letter])   " times")

This prints the following:

e appears 3 times
t appears 2 times
a appears 2 times
h appears 1 times
s appears 1 times
l appears 1 times
m appears 1 times
k appears 1 times
r appears 1 times

CodePudding user response:

There are several issues in you code.

  1. dictionary is not ordered (though in some latest python versions it do preserve the order you add to it), so sorting it makes no sense actually. When you need output something in order, you often need convert to a list type. In below code, the return type is list((k,v))
  2. sorted function needs key parameter, which is often a lambda expression indicating what property of the item to order by.
  3. Sorted object is never used.
import collections

MY_FUN_STR = filter(str.isalpha, (str.lower("ThE_SLATe-Maker")))
frequencies = collections.Counter(MY_FUN_STR)
sorted_key_value_items = sorted(frequencies.items(), reverse=True, key=lambda x: x[1])
for letter, count in sorted_key_value_items:
    print('{} appears {}'.format(letter, count)   " times")

Reference this answer to sort a dict: How do I sort a dictionary by value?

  • Related