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!
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)]
Err...
>>> list(collections.Counter(('5', '5', '4', '5')).items())
[('5', 3), ('4', 1)]
If you want to sort by item numberic/alphabetically ascending:
l = []
for key in sorted(c.iterkeys()):
l.append([key, c[key]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With