I have a Counter that is already ordered by number of occurrences.
counterlist = Counter({'they': 203, 'would': 138, 'your': 134,...}).
But when I do counterlist.keys()
the return list is:
['wirespe', 'four', 'accus',...]
instead of
['they', 'would', 'your',...].
Why?
Accessing Elements in Python Counter To get the list of elements in the counter we can use the elements() method. It returns an iterator object for the values in the Counter.
Python Counter is a subclass of the dict or dictionary class . It keeps track of the frequency of each element in the container . It takes as argument an iterable object (like list) and returns back a dictionary.
Counter is an unordered collection where elements are stored as Dict keys and their count as dict value. Counter elements count can be positive, zero or negative integers. However there is no restriction on it's keys and values. Although values are intended to be numbers but we can store other objects too.
Initializing. Counter supports three forms of initialization. Its constructor can be called with a sequence of items, a dictionary containing keys and counts, or using keyword arguments mapping string names to counts. To create an empty counter, pass the counter with no argument and populate it via the update method.
Another solution without creating an extra class is to take the set of items you have and sort them based on the counted keys. The code below is based on @user3005486:
import collections
#if this is your list
list_to_be_sorted = ['they', 'would', 'they', ...]
#then counterlist = {'would': 203, 'they': 138, 'your': 134}
counterlist = collections.Counter(list_to_be_sorted)
#if you sort this list ascendingly you get ['would', 'would', ..., 'they', 'they', ...etc.]
sorted_words = sorted(counterlist, key: lambda x:-counterlist[x])
distinct_words_from_list = set(list_to_be_sorted)
sorted_distinct_list = sorted(distinct_words_from_list, key: lambda x:-counterlist[x])
#then sorted_distinct_list = ['would', 'they', 'your']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With