Sort Counter by value? - python

0 votes

Is there a pythonic way to sort Counter by value? If so, it is faster than this:

>>> from collections import Counter
>>> x = Counter({'a':1, 'b':2, 'c':3})
>>> sorted(x)
['a', 'b', 'c']
>>> sorted(x.items())
[('a', 1), ('b', 2), ('c', 3)]
>>> [(l,k) for k,l in sorted([(j,i) for i,j in x.items()])]
[('a', 1), ('b', 2), ('c', 3)]
>>> [(l,k) for k,l in sorted([(j,i) for i,j in x.items()], reverse=True)]
[('c', 3), ('b', 2), ('a', 1)

Nov 13, 2018 in Python by findingbugs
• 3,140 points
40 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes

>>> x = Counter({'a':1, 'b':2, 'c':3})
>>> sorted(x.items(), key=lambda k: -k[1]) # Ascending
[('a', 1), ('b', 2), ('c', 3)]

answered Nov 13, 2018 by Priyaj
• 56,140 points

Related Questions In Python

0 votes
1 answer

How to sort Counter by value using python?

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

answered May 22, 2018 in Python by charlie_brown
• 7,710 points
1,212 views
0 votes
1 answer

How to sort dictionary by value python

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

answered Nov 2, 2018 in Python by Nabarupa
49 views
0 votes
1 answer

How do I sort a dictionary by value?

If you construct a dictionary with the ...READ MORE

answered Mar 12 in Python by Trisha
8 views
0 votes
1 answer

Sort list by frequency in python

You can try the following for a ...READ MORE

answered May 13 in Python by SDeb
• 10,780 points
16 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
55 views
0 votes
1 answer

How do I sort a dictionary by value?

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

answered Jul 30, 2018 in Python by Priyaj
• 56,140 points
16 views
+1 vote
1 answer

Reading a large file, line by line in Python

The correct, fully Pythonic way to read ...READ MORE

answered Aug 21, 2018 in Python by Priyaj
• 56,140 points
43 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.