Other than doing list comprehensions of reversed list comprehension, is there a pythonic way to sort Counter by value? If so, it is faster than this:

```>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> sorted(x)
['a', 'b', 'c']
>>> sorted(x.items())
[('a', 5), ('b', 3), ('c', 7)]
>>> [(l,k) for k,l in sorted([(j,i) for i,j in x.items()])]
[('b', 3), ('a', 5), ('c', 7)]
>>> [(l,k) for k,l in sorted([(j,i) for i,j in x.items()], reverse=True)]
[('c', 7), ('a', 5), ('b', 3)``` May 23, 2018 in Python 8,366 views

## 1 answer to this question.

Use the Counter.most_common() method, it'll sort the items for you:

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

It'll do so in the most efficient manner possible; if you ask for a Top N instead of all values, a heapqis used instead of a straight sort:

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

Outside of counters, sorting can always be adjusted based on a key function; .sort() and sorted() both take callable that lets you specify a value on which to sort the input sequence; sorted(x, key=x.get, reverse=True) would give you the same sorting as x.most_common(), but only return the keys, for example:

```>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']```

or you can sort on only the value given (key, value) pairs:

```>>> sorted(x.items(), key=lambda pair: pair, reverse=True)
[('c', 7), ('a', 5), ('b', 3)]``` answered May 23, 2018 by
• 7,710 points

## How to sort dictionary by value python

This would work: d = sorted(data, key = ...READ MORE

## Sort Counter by value? - python

>>> x = Counter({'a':1, 'b':2, 'c':3}) >>> ...READ MORE

## How to get the return value from a thread using python?

FWIW, the multiprocessing module has a nice interface for ...READ MORE

+1 vote

## How to create plots using python matplotlib in IPython notebook?

I think you should try: I used %matplotlib inline in ...READ MORE

## How to slice an array using python numpy? Is there any numpy tutorial which has covered all its operations?

Slicing is basically extracting particular set of ...READ MORE

## How do I sort a dictionary by value?

It is not possible to sort a ...READ MORE