Python Counter keys() return values

While you entered the values in a dictionary in a particular order, a dict doesn't retain any sort of order. .keys() on a dict returns in no particular order. There is an OrderedDict that does retain order, but I don't know how that interacts with Counter.

EDIT:

You may want to use Counter.most_common(). That will return a list of tuples which will be in order.


Counter()

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

is an unordered dict so it does not keep the order in which you added them to the dict. If you want to keep them in order you will need to use an OrderedDict()

If you want an OrderedCounter() then you could do this which I am pulling from here which has an explanation as to why it works.

from collections import *

class OrderedCounter(Counter, OrderedDict):
    pass

counterlist = OrderedCounter({'would': 203, 'they': 138, 'your': 134})

print counterlist.keys()

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']

Tags:

Python

Counter