I am using the collections counter to count each string (they might not be unique) inside lists. The problem is that now I can't access the dictionary, and I am not sure why.
My code is:
from collections import Counter
result1 = Counter(list_final1) #to count strings inside list
If I print result1, output is for example:
Counter({'BAM': 44, 'CCC': 20, 'APG': 14, 'MBI': 11, 'BAV': 10})
To access the number 44 for exampke I would expect to use Counter['BAM']
But this above doesnt work and I get the error:
print (Counter['BAM'])
TypeError: 'type' object is not subscriptable
What am I doing wrong? Thanks a lot.
Use your key
with the variable in which you stored the value of Counter
, in your case result1
. Sample:
>>> from collections import Counter
>>> my_dict = {'BAM': 44, 'CCC': 20, 'APG': 14, 'MBI': 11, 'BAV': 10}
>>> result = Counter(my_dict)
>>> result['BAM']
44
Explaination:
You are doing Counter['BAM']
, i.e making new Counter
object with 'BAM'
as param, which is invalid. Instead if you do Counter(my_dict)['BAM']
, it will also work since it is the same object in which your dict is passed, and you are accessing 'BAM'
key within it