Keyerror in python despite having keyword
Question: I am getting `KeyError:'Fellow'` after running following program despite this
keyword exist in the `text4`.

    
    
      import nltk;
      from nltk.book import *
      cnt = {}
      for word in text4:
           cnt[word] += 1
    
      print cnt['citizen']
    

Error:

    
    
    Traceback (most recent call last):
      File "wordcount.py", line 5, in <module>
        cnt[word] += 1
    KeyError: 'Fellow'
    

However, if I do this I can see that 'Fellow' keyword is in fact present.

    
    
      >>> text4.count('Fellow')
          24
    

Could anyone please suggest what am I doing wrong ?


Answer: `'Fellow'` exists in `text4` but **not** in `cnt`, which is an empty
dictionary with no keys. The minimal fix is:

    
    
    for word in text4:
           if word not in cnt:
               cnt[word] = 0
           cnt[word] += 1
    

But it's probably easier to use
[`collections.Counter`](https://docs.python.org/2/library/collections.html#collections.Counter):

    
    
    from collections import Counter
    
    cnt = Counter(text4)
    

