47

I have a counter that looks a bit like this:

Counter: {('A': 10), ('C':5), ('H':4)}

I want to sort on keys specifically in an alphabetical order, NOT by counter.most_common()

is there any way to achieve this?

falsetru
  • 357,413
  • 63
  • 732
  • 636
corvid
  • 10,733
  • 11
  • 61
  • 130

5 Answers5

78

Just use sorted:

>>> from collections import Counter
>>> counter = Counter({'A': 10, 'C': 5, 'H': 7})
>>> counter.most_common()
[('A', 10), ('H', 7), ('C', 5)]
>>> sorted(counter.items())
[('A', 10), ('C', 5), ('H', 7)]
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    I agree, knowing that the iterator on a dict yields the keys, not the values, then the keys will get sorted. – DevLounge Jul 29 '13 at 18:26
  • 7
    Note, this transforms Counter to a list – crypdick Mar 06 '20 at 03:31
  • 1
    @crypdick, Yes it does, and it should be. Because In `Python < 3.7`, the order dictionary key is not guaranteed. https://mail.python.org/pipermail/python-dev/2017-December/151283.html , https://docs.python.org/3/whatsnew/3.7.html – falsetru Mar 06 '20 at 04:45
14
>>> from operator import itemgetter
>>> from collections import Counter
>>> c = Counter({'A': 10, 'C':5, 'H':4})
>>> sorted(c.items(), key=itemgetter(0))
[('A', 10), ('C', 5), ('H', 4)]
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
  • 2
    This works, however, itemgetter is useful to sort a list of tuples or a list of list, but on a dict it is useless, sorted(c) is equivalent to sorted(c.keys()) – DevLounge Jul 29 '13 at 18:27
4
sorted(counter.items(),key = lambda i: i[0])

for example:

arr = [2,3,1,3,2,4,6,7,9,2,19]
c = collections.Counter(arr)
sorted(c.items(),key = lambda i: i[0])

outer: [(1, 1), (2, 3), (3, 2), (4, 1), (6, 1), (7, 1), (9, 1), (19, 1)] if you want to get the dictionary format,just

dict(sorted(c.items(),key = lambda i: i[0]))
Calab
  • 41
  • 2
2

To get values as list in sorted order

array              = [1, 2, 3, 4, 5]
counter            = collections.Counter(array)
sorted_occurrences = list(dict(sorted(counter.items())).values())
0

In Python 3, you can use the most_common function of collections.Counter:

x = ['a', 'b', 'c', 'c', 'c', 'd', 'd']
counts = collections.Counter(x)
counts.most_common(len(counts))

This uses the most_common function available in collections.Counter, which allows you to find the keys and counts of n most common keys.

wwwilliam
  • 9,142
  • 8
  • 30
  • 33