Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'map' object is not subscriptable error in Python 3

I am trying to use the FreqDist that is part of NLTK in Python. I tried this sample code:

fdist1 = FreqDist(text1)
vocabulary1 = fdist1.keys()
vocabulary1[:50]

but the last line gives me this error:

TypeError: 'map' object is not subscriptable

I think the code runs fine on Python 2, but on Python 3 (that I have) it give the above error.

Why is this error and how to resolve it? I appreciate any help on this.

like image 574
TJ1 Avatar asked Jul 03 '26 07:07

TJ1


2 Answers

In Python 3 .keys() returns an iterator, which you can't slice. Convert it to a list before slicing.

fdist1 = FreqDist(text1)
vocabulary1 = fdist1.keys()
x = list(vocabulary1)[:50]
# or...
vocabulary1 = list(fdist1.keys())
x = vocabulary1[:50]
like image 148
Tim Avatar answered Jul 04 '26 21:07

Tim


You have to convert it to list first:

new_vocab= list(vocabulary1)
...= new_vocab[:50]
like image 30
Jack_of_All_Trades Avatar answered Jul 04 '26 22:07

Jack_of_All_Trades



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!