In Python 2.7, I want to iterate over a collections.Counter
instance in descending count order.
>>> import collections >>> c = collections.Counter() >>> c['a'] = 1 >>> c['b'] = 999 >>> c Counter({'b': 999, 'a': 1}) >>> for x in c: print x a b
In the example above, it appears that the elements are iterated in the order they were added to the Counter instance.
I'd like to iterate over the list from highest to lowest. I see that the string representation of Counter does this, just wondering if there's a recommended way to do it.
Counter is a subclass of dict that's specially designed for counting hashable objects in Python. It's a dictionary that stores objects as keys and counts as values. To count with Counter , you typically provide a sequence or iterable of hashable objects as an argument to the class's constructor.
Python Counter is a container that keeps track of the number of occurrences of a value. Here are some key takeaways: Python Counter is a subclass of the dict or dictionary class. Counts are always displayed in descending order.
You can iterate over c.most_common()
to get the items in the desired order. See also the documentation of Counter.most_common()
.
Example:
>>> c = collections.Counter(a=1, b=999) >>> c.most_common() [('b', 999), ('a', 1)]
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