Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Counter object into a usable list of pairs?

The code I have now:

from collections import Counter
c=Counter(list_of_values)

returns:

Counter({'5': 5, '2': 4, '1': 2, '3': 2})

I want to sort this list into numeric(/alphabetic) order by item, not number of occurrences. How can I convert this into a list of pairs such as:

[['5',5],['2',4],['1',2],['3',2]]

Note: If I use c.items(), I get: dict_items([('1', 2), ('3', 2), ('2', 4), ('5', 5)]) which does not help me...

Thanks in advance!

like image 784
user1459435 Avatar asked Jun 15 '12 17:06

user1459435


3 Answers

You can just use sorted():

>>> c
Counter({'5': 5, '2': 4, '1': 2, '3': 2})
>>> sorted(c.iteritems())
[('1', 2), ('2', 4), ('3', 2), ('5', 5)]
like image 121
stranac Avatar answered Oct 17 '22 09:10

stranac


Err...

>>> list(collections.Counter(('5', '5', '4', '5')).items())
[('5', 3), ('4', 1)]
like image 34
Ignacio Vazquez-Abrams Avatar answered Oct 17 '22 09:10

Ignacio Vazquez-Abrams


If you want to sort by item numberic/alphabetically ascending:

l = []
for key in sorted(c.iterkeys()):
    l.append([key, c[key]])
like image 42
Queequeg Avatar answered Oct 17 '22 09:10

Queequeg