How to sort the frequency of each letter in a descending order Python?

512 views Asked by At
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
2

There are 2 answers

0
BrokenBenchmark On

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
2
Lei Yang On

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 apply sorted to a dictionary, it returns the keys list. Considering you need both key and value in the print, sorting .items() is better choice. example:
d = {'b': 2, "a": 1}
print(sorted(d))
# ['a', 'b']
print(sorted(d.items()))
# [('a', 1), ('b', 2)]

  1. sorted function has a key parameter, which is often a lambda expression indicating what property of the item to order by. If not specified, will sort by dictionary.key by default, but in your case you want sort by dictionary.value, so you need the key= parameter.
  2. 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?