Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Counter by frequency, then alphabetically in Python

I am trying to use counter to sort letters by occurrence, and put any that have the same frequency into alphabetical order, but I can't get access to the Value of the dictionary that it produces.

letter_count = collections.Counter("alphabet")
print(letter_count)

produces:

Counter({'a': 2, 'l': 1, 't': 1, 'p': 1, 'h': 1, 'e': 1, 'b': 1})

How can I get it ordered by frequency, then by alphabetical order, so everything that shows up only once is in alphabetical order?

like image 991
iFunction Avatar asked May 19 '17 17:05

iFunction


People also ask

How do I sort in alphabetical order in Python?

Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.


2 Answers

It sounds like your question is how to sort the entire list by frequency, then break ties alphabetically. You can sort the entire list like this:

>>> a = sorted(letter_count.items(), key=lambda item: (-item[1], item[0]))
>>> print(a)
# [('a', 2), ('b', 1), ('e', 1), ('h', 1), ('l', 1), ('p', 1), ('t', 1)]

If you want the output to be a dict still, you can convert it into a collections.OrderedDict:

>>> collections.OrderedDict(a)
# OrderedDict([('a', 2),
#              ('b', 1),
#              ('e', 1),
#              ('h', 1),
#              ('l', 1),
#              ('p', 1),
#              ('t', 1)])

This preserves the ordering, as you can see. 'a' is first because it's most frequent. Everything else is sorted alphabetically.

like image 127
Arya McCarthy Avatar answered Sep 23 '22 23:09

Arya McCarthy


You can sort the input before passing it to the counter.

>>> Counter(sorted("alphabet")).most_common()
[('a', 2), ('b', 1), ('e', 1), ('h', 1), ('l', 1), ('p', 1), ('t', 1)]
like image 36
sabacherli Avatar answered Sep 22 '22 23:09

sabacherli