How to convert a Counter object to a useful list of pairs?

The code I have is:

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 by numerical (/ alphabetic) order by position, not by the number of occurrences. How can I convert this to a list of pairs, for example:

 [['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)]) that doesn't help me ...

Thanks in advance!

+8
source share
5 answers

Err ...

 3>> list(collections.Counter(('5', '5', '4', '5')).items()) [('5', 3), ('4', 1)] 
+14
source

If you want to sort by number / alphabetically ascending:

 l = [] for key in sorted(c.iterkeys()): l.append([key, c[key]]) 
+1
source

You can simply use sorted() :

 >>> c Counter({'5': 5, '2': 4, '1': 2, '3': 2}) >>> sorted(c.iteritems()) [('1', 2), ('2', 4), ('3', 2), ('5', 5)] 
0
source

Convert the counter into a dictionary, and then divide it into two separate lists, for example:

 c=dict(c) key=list(c.keys()) value=list(c.values()) 
0
source
 >>>RandList = np.random.randint(0, 10, (25)) >>>print Counter(RandList) 

outputs something like ...

 Counter({1: 5, 2: 4, 6: 4, 7: 3, 0: 2, 3: 2, 4: 2, 5: 2, 9: 1}) 

And with that ...

 >>>thislist = Counter(RandList) >>>thislist = thislist.most_common() >>>print thislist [(1, 5), (2, 4), (6, 4), (7, 3), (0, 2), (3, 2), (4, 2), (5, 2), (9, 1)] >>>print thislist[0][0], thislist[0][1] 1 5 
-3
source

All Articles