collections counter python can't access the key
<p>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.</p>

<p>My code is:</p>

<pre><code>from collections import Counter
result1  = Counter(list_final1) #to count strings inside list
</code></pre>

<p>If I print result1, output is for example:</p>

<pre><code>Counter({'BAM': 44, 'CCC': 20, 'APG': 14, 'MBI': 11, 'BAV': 10})
</code></pre>

<p>To access the number 44 for exampke I would expect to use Counter['BAM']</p>

<p>But this above doesnt work and I get the error:</p>

<pre><code>    print (Counter['BAM'])
TypeError: 'type' object is not subscriptable
</code></pre>

<p>What am I doing wrong? Thanks a lot.</p>

<p>Use your <code>key</code> with the variable in which you stored the value of <code>Counter</code>, in your case <code>result1</code>. Sample:</p>

<pre><code>&gt;&gt;&gt; from collections import Counter
&gt;&gt;&gt; my_dict = {'BAM': 44, 'CCC': 20, 'APG': 14, 'MBI': 11, 'BAV': 10}
&gt;&gt;&gt; result = Counter(my_dict)
&gt;&gt;&gt; result['BAM']
44
</code></pre>

<p><strong>Explaination</strong>:</p>

<p>You are doing <code>Counter['BAM']</code>, i.e making new <code>Counter</code> object with <code>'BAM'</code> as param, which is invalid. Instead if you do <code>Counter(my_dict)['BAM']</code>, it will also work since it is the same object in which your dict is passed, and you are accessing <code>'BAM'</code> key within it </p>

python python-collections