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?
You can try this:
This code creates a list of all letters that occur only once by using list comprehension, and then prints them all. items() returns a key-value pair, which can be used to determine if the value of a key is equal to one.
For the sake of completeness, to get the single-occurrence letters in alphabetical order:
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:
If you want the output to be a dict still, you can convert it into a
collections.OrderedDict
:This preserves the ordering, as you can see.
'a'
is first because it's most frequent. Everything else is sorted alphabetically.