Counting items inside tuples in Python
<p>I am fairly new to python and I could not figure out how to do the following. </p>

<p>I have a list of (word, tag) tuples </p>

<pre><code>a = [('Run', 'Noun'),('Run', 'Verb'),('The', 'Article'),('Run', 'Noun'),('The', 'DT')]
</code></pre>

<p>I am trying to find all tags that has been assigned to each word and collect their counts. For example, word "run" has been tagged twice to 'Noun' and once to 'Verb'. </p>

<p>To clarify: I would like to create another list of tuples that contains (word, tag, count)</p>

<p>You can use <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a>:</p>

<pre><code>&gt;&gt;&gt; import collections

&gt;&gt;&gt; a = [('Run', 'Noun'),('Run', 'Verb'),('The', 'Article'),('Run', 'Noun'),('The', 'DT')]
&gt;&gt;&gt; counter = collections.Counter(a)
Counter({('Run', 'Noun'): 2, ('Run', 'Verb'): 1, ... })

&gt;&gt;&gt; result = {}
&gt;&gt;&gt; for (tag, word), count in counter.items():
...     result.setdefault(tag, []).append({word: count})

&gt;&gt;&gt; print(result)
{'Run': [{'Noun': 2}, {'Verb': 1}], 'The': [{'Article': 1}, {'DT': 1}]}
</code></pre>

python tuples