Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to iterate over a collections.Counter() instance in descending order?

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.

like image 998
Inactivist Avatar asked Jun 14 '12 16:06

Inactivist


People also ask

What does counter () do in Python?

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.

Does counter have order python?

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.


1 Answers

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)] 
like image 76
Sven Marnach Avatar answered Sep 20 '22 05:09

Sven Marnach