user3760644 user3760644 - 1 year ago 235
Python Question

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

I am following instructions for a class homework assignment and I am 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)

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?
Any help is greatly appreciated :)

Answer Source

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

vocab = list(fdist1.keys())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download