Python Counter keys() return values

counterpython

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?

Best Answer

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()