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 tried your code and got a <code>KeyError: ''</code> which happens because your initial bigram has an empty string at position 0 and <code>''</code> is not in your unigrams dictionary. I didn't see a <code>TypeError</code> so that may be from somewhere else in your code. </p>

<p>That said, various other comments: </p>

<ol>
<li><p>You seem to understand what a <code>collections.Counter</code> does, but you're haphazardly trying to do it yourself while building <code>uni</code> -- you can replace your first chunk of code with:</p>

<p><code>unigrams = Counter(sp)</code></p></li>
<li><p>You can use <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip</code></a> to iterate over pairs and construct your bigrams that way, instead of DIY looping it, which also gets rid of your <code>''</code> issue:</p>

<p><code>bigrams = Counter(zip(sp, sp[1:]))</code></p></li>
</ol>

<p>So your code becomes:</p>

<pre><code>sp = corpus.split()
unigrams = Counter(sp)
bigrams = Counter(zip(sp, sp[1:]))

for bigram, count in bigrams.most_common():
    # etc. 
</code></pre>

python nlp tuples n-gram