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

PythonPython 3.xDictionaryKeyNltk

Python Problem Overview


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)
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?

Python Solutions


Solution 1 - Python

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())

Solution 2 - Python

I am using python 3.5 and I meet the same problem of TypeError.

Using vocab = list(fdist1.keys()) does not give me the top 50 most frequently used words.
But fdist1.most_common(50) does.

Further,if you just want to show those top 50 words not with their frequency,you can try :

[word for (word, freq) in fdist1.most_common(50)]

Solution 3 - Python

To print the most frequently used 200 words use: fdist1.most_common(200) The above line of code will return the 200 most frequently used words as key-frequency pair.

Solution 4 - Python

If you want to get elements as keys and values (word and frequency), you can use:

list(fdist1.items())[:200]

Solution 5 - Python

If your using python 3 try:

fdist1.most_common(200)

instead, to get the 200 most frequent words.

Solution 6 - Python

fdist1 = FreqDist(NSmyText)

vocab=fdist1.keys()

This code is using in Python2.7. So you should do some change. dic.keys() returns an iteratable. So using:

list(fdist1.keys())

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3760644View Question on Stackoverflow
Solution 1 - PythonKlaus D.View Answer on Stackoverflow
Solution 2 - PythonRoy ChenView Answer on Stackoverflow
Solution 3 - PythonShikhar GuptaView Answer on Stackoverflow
Solution 4 - PythonzaroobaView Answer on Stackoverflow
Solution 5 - Pythonlasu mosesView Answer on Stackoverflow
Solution 6 - PythonHeronView Answer on Stackoverflow