Cannot access elements in a list in Python
<p>I working with bigrams and unigrams. </p>

<p>My bigrams are a counter of tuples and my unigrams are a list, where </p>

<pre><code> uni['some key']=count
</code></pre>

<p>I am trying to do the follwing</p>

<pre><code> for b,countB in bigrams.most_common()
      key=b[0] # this is guaranteed to be a key for my unigrams
      uniCount=uni[key]
</code></pre>

<p>The following error occurs:</p>

<pre><code> TypeError: tuple indeces must be integers or slices, not str
</code></pre>

<p>I am confused.  Why should this be a problem? uni is essentially a hash, its key values are strings. How can I access u[key]?</p>

<p>edit: full code</p>

<pre><code> # corpus is a string containing my corpus
 sp=corpus.split()

 uni={}
 for t in sp:
      try:
           uni[t]+=1
      except:
           uni[t]=0
 prev=''
 big=[]
 for t in sp:
      tup=(prev,t)
      big.append(tup)
      prev=t

 bigrams=collections.Counter(big)

 for b,countB in bigrams.most_common():
      key=b[0]
      uniCount=uni[key]
</code></pre>

<p>You are making the mistake of using a tuple when you perhaps need a dictionary. As the error message state, tuples cannot be indexed by a string key - you are expected to use numeric indices.</p>

<p>A dict will let you use string keys as you appear to want to.</p>

<pre><code>d = {}
d['some key] = 23
</code></pre>

<p>Your updated code gives a much better idea of what you are doing. You start by creating a dict of word counts in <code>uni</code>. I think the line that reads</p>

<pre><code>uni[t] = 0
</code></pre>

<p>should in fact read</p>

<pre><code>uni[t] = 1
</code></pre>

<p>because when that branch is executed you are detecting the first occurrence of a word. Next you create a list of bigram tuples in <code>big</code>, and then you count those bigrams.</p>

<p>I get a bit lost with the final <code>for</code> loop, though, where  <code>b</code> will be the key of a <code>Counter</code> item and <code>countB</code> to be the count. So <code>key</code> will be the first word of the bigram, and <code>uniCount</code> will be the number of times that word appeared in the corpus. Having established these value you then proceed to do nothing with them, and move on to the next most common bigram.</p>

<p>Perhaps it's time to do some printing in that final loop? The code as published otherwise looks reasonable.</p>

python nlp tuples n-gram