Alex Rivera | Logout

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

Asked 2012-06-15T17:59:51.933
14

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!

Edit
Report

2 Answers

20

Err...

>>> list(collections.Counter(('5', '5', '4', '5')).items())
[('5', 3), ('4', 1)]
answered 2012-06-15T18:02:57.947
1

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

l = []
for key in sorted(c.iterkeys()):
    l.append([key, c[key]])
answered 2012-06-15T18:38:27.000

Your Answer