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.