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>I have executed your code with <code>corpus = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore"</code> since you said the error was a related to <code>uni</code> being a tuple but it actually is a dictionary.</p>

<p>The error I got is different, it is a <code>KeyError</code> on <code>uniCount=uni[key]</code> because you are creating a list of tuples <code>(previous word, word)</code> and the first word of <code>corpus</code> has previous word set as an empty string (<code>prev=''</code> is the initial state). </p>

<p>The key at the <code>uniCount=uni[key]</code> line is equal to the first item of the tuple (<code>key=b[0]</code>) so as there is no key <code>''</code> in the <code>uni</code> dictionary it is throwing a <code>KeyError</code>.</p>

<p>You may want to get the word, not the previous word of the tuple to be the key used in <code>uni</code>.</p>

python nlp tuples n-gram