0

Is it possible to access specific item of Counter?

from collections import Counter
s=['a','b','r','e', 'a', 'r','r']
print(Counter(s))

Output

Counter({'r': 3, 'a': 2, 'b': 1, 'e': 1})

I want to access ('a':2) or for example ('a': 2, 'b': 1) items, how to do it without using for loop?

I couldn't access ('a':2) using print(Counter(s).items([1])).


My answer:

s=sorted(['a','e','r','b', 'a', 'r','r'])

x=Counter(s)
y={k: v for k, v in sorted(x.items(), key=lambda item: item[1], reverse=True)}

i=0
for key,value in y.items():
    if i<3:
        print(str(key) + " " + str(value))
        i+=1

I sorted the list in the beginning so that if the values of the items are equal, then the alphabetic order will be preserved.

Lee
  • 169
  • 1
  • 9

3 Answers3

1

Counter has a most_common method that returns a list of key-value pairs in decreasing order of their count.

>>> s = ['a','b','r','e', 'a', 'r','r']
>>> Counter(s).most_common(3)
[('r', 3), ('a', 2), ('b', 1)]
chepner
  • 497,756
  • 71
  • 530
  • 681
  • if you change 'b' and 'e' inside list s, then your code prints [('r', 3), ('a', 2), ('e', 1)], but since both b and e have same value, I want to print b, since it is first in alphabetic order – Lee Aug 03 '22 at 12:45
  • Would sorting the input first be sufficient? `Counter(sorted(s)).most_common(3)`. `Counter` is breaking ties based on which key was added first, not necessarily which values are lexicographically smaller. – chepner Aug 03 '22 at 13:19
  • I did exactly the same thing and yes it works, I have added my new answer to the question. thanks! – Lee Aug 03 '22 at 13:31
0

Try this?

>>> c = Counter(s)
>>> find = 'a'
>>> (find, c[find])
('a', 2)
The Thonnu
  • 3,578
  • 2
  • 8
  • 30
0

This should do the trick:

import json
from collections import Counter
counter = Counter(['a','b','r','e', 'a', 'r','r'])
sorted_data = {
    letter: occurrences
    for letter, occurrences in sorted(
        counter.items(),
        key=lambda item: item[1],
        reverse=True
    )
}
print(json.dumps(sorted_data, indent=4))
OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87
  • Or, just sort the input to `Counter`, then dump `dict(counter.most_common())`. – chepner Aug 03 '22 at 12:33
  • if you change 'b' and 'e' inside list s, then your code prints [('r', 3), ('a', 2), ('e', 1), ('b',1)], but since both b and e have same value, I want to print b first, since it is first in alphabetic order – Lee Aug 03 '22 at 12:47