Search code examples
pythonpython-3.xdictionarykeynltk

NLTK python error: "TypeError: 'dict_keys' object is not subscriptable"


I'm following instructions for a class homework assignment and I'm supposed to look up the top 200 most frequently used words in a text file.

Here's the last part of the code:

fdist1 = FreqDist(NSmyText)
vocab=fdist1.keys()
vocab[:200]

But when I press enter after the vocab 200 line, it returns:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dict_keys' object is not subscriptable

Any suggestions on how to fix this so it can correctly return an answer?


Solution

  • Looks like you are using Python 3. In Python 3 dict.keys() returns an iterable but not indexable object. The most simple (but not so efficient) solution would be:

    vocab = list(fdist1.keys())[:200]
    

    In some situations it is desirable to continue working with an iterator object instead of a list. This can be done with itertools.islice():

    import itertools
    vocab_iterator = itertools.islice(fdist1.keys(), 200)