×

Search anything:

Different ways to sort a counter in Python

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

The different ways to sort a counter in Python are:

  • Using the Counter.most_common([N]) method
  • Using .sorted() to sort just the keys
  • Using .sorted() to sort values on the given (key,value) pairs

The official python document defines a counter as follows:

“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. Counts are allowed to be any integer value including zero or negative counts. ”

Syntax:

class collections.Counter([iterable-or-mapping]) 

Sorting Counters

Counters are very useful as is, with the added functionality of easy sorting ,it saves so much time and avoids reinventing the wheel. So the next time you need to sort a counter just refer to this article to know everything there is to it.
In the methods mentioned below, I've explained how to use some built-in python functions along with their time complexities so you can choose which ever is suitable to your application.

Here are the different ways of sorting a counter:

1.Using the Counter.most_common([N]) method
2.Using .sorted() to sort just the keys
3.Using .sorted() to sort values on the given (key,value) pairs

  1. Using the Counter.most_common([N]) method
    It essentially returns a sorted list of the counts from the most common element to the least common element in the counter. If N is omitted it returns all elements in the counter and if N is mentioned it returns only the first N elements of the returned list. Elements with equal counts are ordered arbitrarily.

Syntax:

Counter_object.most_common([n])

Time Complexity:

If N value is omitted: Θ(n log n)
If the N value is greater than 1: Θ(n log N)
Where n is the number of entries in the counter

Example Code Snippet where N value is not mentioned:

from collections import Counter
x = Counter({'a':5, 'b':3, 'c':7})
print(x.most_common())
-->[('c', 7), ('a', 5), ('b', 3)]

Example code snippet where N value is mentioned:

x.most_common(1)
-->[('c', 7)]

If you ask for a Top N instead of all values, a heapq is used instead of a straight sort.

  1. Using .sorted() to sort just the keys
    The .sorted() method is used to sort any iterable.It always returns a sorted list

Syntax:

sorted(iterable, key=None, reverse=False)

Time Complexity:
Both,average and worst case complexities:Θ(n log n)
Where n is the number of entries in the counter

Here the iterable is the counter object.Key takes a function for sorting. Here we've used .get to sort by the values in the counter object. Reverse is an optional parameter.If not mentioned it will sort in ascending order. I mentioned it'll sort in descending order.
This method would give you the same result as x.most_common(), but only return the keys, for example:

from collections import Counter
x = Counter({'a':5, 'b':3, 'c':7})
sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']
  1. Using .sorted() to sort values on the given (key,value) pairs
    Here I've used the same method as in method 2 but returning both the key as well as the values. The iterable passed here iterates through all the (key,value) pairs and sorts them according to their values.
sorted(x.items(), key=lambda pair: pair[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]

With this article at OpenGenus, you must have the complete idea of Different ways to sort a counter in Python. Enjoy.

Different ways to sort a counter in Python
Share this