0

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.

Gonzalo
  • 1,084
  • 4
  • 20
  • 40

1 Answers1

2

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

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • humm,, it works! But I didnt understand.. it means that this dict created by the collections counter is not the same as any other dict? Could you elaborate please. – Gonzalo Aug 26 '16 at 08:22
  • It is same. But 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 – Moinuddin Quadri Aug 26 '16 at 08:26